Search code examples
androidandroid-fragmentsandroid-listfragment

ListFragment "Content view not yet created" after detach attach


I'm new in android programming. I tried ListFragment populated from database, and it works well.
I could display the values, but when I try to refresh the view by detaching and attaching the fragment again, got error content view not yet created on getListView() which I put on onActivityCreated.
Any ideas?

public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  listView = getListView();

  db = new DatabaseAccess(getActivity().getApplicationContext());
  List<Contact> contacts = db.getAllContacts();

  if (contacts.size() > 0) {
    List<Map<String, String>> contactList = new ArrayList<Map<String, String>>();
    for (Contact con : contacts) {
      Map<String, String> data = new HashMap<String, String>(2);
      data.put("name", con.getName());
      data.put("number", con.getNumber());
      contactList.add(data);
    }
    SimpleAdapter adapter = new SimpleAdapter(getView().getContext(), contactList, android.R.layout.simple_list_item_2, new String[] {"name", "number"}, new int[] {android.R.id.text1, android.R.id.text2});

    listView.setAdapter(adapter);
  } else {
    setEmptyText("Masih belum ada kontak");
  }
  setListShown(true);
  db.closeDB();
}

when I try to refresh the fragment

void refreshFragment() {
  Fragment frg = getFragmentManager().findFragmentById(R.id.fragment);
  FragmentTransaction fragTransaction = this.getFragmentManager().beginTransaction();
  fragTransaction.detach(frg);
  fragTransaction.attach(frg);
  fragTransaction.commit();
}

Solution

  • To summarize:

    1. Attach/Detach isn't a correct way of refreshing the view
    2. find the Fragment and call a refresh function to update the content
    3. setListShow - doesn't need to be called, the list is by default invisible until a call to setAdapter is made - then if there is content it will become visible.
    4. Call the setListAdapter also if the adapter is empty.

    To refresh the list you don't need to recreate everything just update the adapter content and call the invalidateDataSet function.