Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListFragment doesn't save the bundle in onSaveInstanceState()/doesn't retrieve bundle in onActivityCreated()

I'm new to android and I'm facing the following problem. I'm developing for both, Android 2 and 3, and this is why I use fragments. However to make the app working on Android 2 devices I import android.support.v4.app.ListFragment. I need to maintain selection within my ListFragment when orientation of the screen changes. I'm overriding onSaveInstanceState() method and put an int into the bundle. When the screen is rotated, this method is called and the int is added to the bundle. However when onActivityCreated() is called, its bundle is null. I am following the example provided on Android website: http://developer.android.com/reference/android/app/Fragment.html, but as mentioned above - after onSaveInstanceState() is called, the bundle in onActivityCreated() is still null.

Here's the code:

import android.support.v4.app.ListFragment;
public class VisitsHomeFragment extends ListFragment {
    private int selectedPosition = -1;  

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
          if (savedInstanceState.containsKey("SELECTED_POSITION")) {
                selectedPosition = savedInstanceState.getInt("SELECTED_POSITION");
          }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("SELECTED_POSITION", selectedPosition);
    }
}

I would appreciate any help with this problem.

like image 470
Maria Avatar asked Jul 27 '11 14:07

Maria


3 Answers

I had the same problem, adding android:id to the fragment element in the layout file fixed this issue.

It seems FragmentManager uses the id to send the appropriate bundle when recreating a fragment.

like image 117
Gallal Avatar answered Nov 20 '22 10:11

Gallal


Make sure you're not calling setRetainInstance(true) in the Fragment. After a little experimentation I pinpointed this as being the error in my code. The downside of having to do it this way is one has to manually bundle all instance data.

After removing the method call and updating my onSaveInstanceState to parcel all of my instance variables, I can now restore list position on rotation.

like image 3
Mr. S Avatar answered Nov 20 '22 10:11

Mr. S


I had the same problem, and I eventually tracked it down to having different android:id attribute values on the fragment elements in the two different layouts (portrait and landscape).

like image 2
JimP Avatar answered Nov 20 '22 10:11

JimP