1

I call getListView() in OnActivityCreated() in my ListFragment. It works fine, but if I rotate the device screen and call getListView() again it returns null.

This is the ListFragment code :

public class MyListFragment extends ListFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.my_list_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ListView list = getListView();

        if (list != null) {
            //List is not null!
        }
        else {
            //List is null, there is an error.
        }
    }

}

this is the layout xml (my_list_fragment.xml):

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Amith
  • 6,818
  • 6
  • 34
  • 45
Kfir Guy
  • 2,545
  • 2
  • 14
  • 22

2 Answers2

5

I think you should call it in onViewCreated():

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ListView list = getListView();

    ...
}
Kfir Guy
  • 2,545
  • 2
  • 14
  • 22
Aron Lorincz
  • 1,677
  • 3
  • 19
  • 29
1

this was my solution:

in my ListFragment I overrode the onCreate method like this...

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setRetainInstance(true); // handle rotations gracefully

    ...
}

in my FragmentActivity I added a tag to the FragmentManager in my onCreate method like this...

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    ...

    // create or retrieve the venue list fragment
    final String venueListTag = VenueListFragment.class.getName();
    final FragmentManager fragmentManager = getSupportFragmentManager();
    VenueListFragment venueListFragment = (VenueListFragment) fragmentManager.findFragmentByTag(venueListTag);
    if (venueListFragment == null) {
        venueListFragment = new VenueListFragment();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.main, venueListFragment, venueListTag);
        fragmentTransaction.commit();
    }

    ...
}

here is more about setRetainInstance if you're interested. Im not sure if the android team frowns upon using setRetainInstance but they sure do keep it a secret

Community
  • 1
  • 1
Evan
  • 29
  • 1