0

Здравствуйте! Пытаюсь заполнить данными фрагмент листвью. Программа запускается корректно, но когда открываю фрагмент там нет данных(показывает экран с моим TextView и надписью "Нет данных"), при дебаге видно, что пустой сам листвью, т.е. в адаптор данные поступили. Посмотрите код пожалуйста.

public class MyEmployeFragment extends Fragment {

    MyTask task;
    String employer_id;
    String employer_name;
    String str=null;
    // имена атрибутов для Map
    final String ATTRIBUTE_ID   = "p_id";
    final String ATTRIBUTE_NAME = "p_name";
    ListView listView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                                     Bundle savedInstanceState)  {

        task    = new MyTask();
        task.execute();

        // Creating view correspoding to the fragment
        View v = inflater.inflate(R.layout.my_employe, container, false);

        // Updating the action bar title
        getActivity().getActionBar();
        String[] userId = {"1","2","3"};

        String[] userName = {"Nadezhd","Vasya", "hardcore"};

        ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
                userId.length);
        Map<String, Object> m;
        for (int i = 0; i < userId.length; i++) {
            m = new HashMap<String, Object>();
            m.put(ATTRIBUTE_ID, userId[i]);
            m.put(ATTRIBUTE_NAME, userName[i]);
            data.add(m);
        }

        // массив имен атрибутов, из которых будут читаться данные
        String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME};
        // массив ID View-компонентов, в которые будут вставлять данные
        int[] to = {R.id.tw_employe_id, R.id.tw_employe_name};

        // создаем адаптер
        SimpleAdapter sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
              from, to);

        // определяем список и присваиваем ему адаптер
        listView = (ListView) v.findViewById(R.id.lv_employee_list);

        listView.setAdapter(sAdapter);

    return v;
}

}

list _ item _ employe.xml

      <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:paddingLeft="20dp"
        android:paddingTop="20dp"
        android:id="@+id/tw_employe_id" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/tw_employe_name"
        android:paddingLeft="20dp" />
</LinearLayout>

my _ employe .xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lv_employee_list"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text=""
        android:layout_marginTop="150dp"
        android:id="@+id/tw_employe_name"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:id="@id/android:empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/empty">
    </TextView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text=""
        android:layout_marginLeft="14dp"
        android:id="@+id/tw_employe_id"
         />

</LinearLayout>

1 ответ 1

1
public class MyEmployeFragment extends Fragment

Заменить на

public class MyEmployeFragment extends ListFragment

В описании Layout идентификатор ListView заменить на @android:id/list

Соответственно в коде не искать ListView, а просто использовать метод getListView().

Обычный Fragment не умеет автоматически производить манипуляции с empty/list.

6
  • @Deadkenny большое спасибо за ответы! Лично Ваши, мне в который раз, помогают! Все заработало. Только почему, сейчас выводит только одну строку данных. Т.к. я получаю вот такой массив: {"p_result":"ok","p_item": [{"p_id":132,"p_name":"Николай","p_last_name":"Ереминко"}, {"p_id":133,"p_name":"Светлана","p_last_name":"Федорченко"}]} Выводит в лист только : 133 Светлана Федорченко
    – Garf1eld
    18 апр 2014 в 10:16
  • Для этого надо видеть код из MyTask
    – Deadkenny
    18 апр 2014 в 10:24
  • @Deadkenny @Override protected Void doInBackground(Void... params) { String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113"; HttpActivity _http = new HttpActivity("sd", "asd"); _http.set_addr_protocol("abc"); _http.add_param("query", "spr_employee_get"); _http.add_param("p_guid", s); _http.send(); employer_name = _http.getArrayParamValue("p_name"); employer_id = _http.getArrayParamValue("p_id"); employer_last_name = _http.getArrayParamValue("p_last_name");
    – Garf1eld
    18 апр 2014 в 10:28
  • onPre execute и post пустые
    – Garf1eld
    18 апр 2014 в 10:28
  • в целом переписал кучу кода, теперь проблема в том, как сначала загрузить данные, а потом только отобразить их. в методе onAttach прописал task.execute(); но смысл не поменялся
    – Garf1eld
    18 апр 2014 в 12:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.