Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android, retain and restore Fragment state after replace

I have an activity hosting 2 fragments, and I don't use viewpager. The way I do is like below. When I move from Fragment1 to Fragment2, I see onSaveInstanceState of Fragment1 is called. However, when I move from Fragment2 back to Fragment1, onCreate() and onCreateView() are called with savedInstanceState as null. I already try setRetainState(true) in onCreate() of fragments. What am I missing? Thanks.

P.S: SO has a question that's marked duplicate Saving Fragment's state after replacing Fragment but the original question doesn't exist any more.

switch (event.option) {
            case 1:
                getSupportActionBar().show();
                if (frag1 == null)
                    frag1 = new Fragment1();
                fragmentManager.beginTransaction().replace(R.id.v4_main_content, frag1).commit();
                break;
            case 2:
                getSupportActionBar().hide();
                if (frag2 == null)
                    frag2 = new Fragment2();
                fragmentManager.beginTransaction().replace(R.id.v4_main_content, frag2).commit();
                break; 
}

Update: code as required in the comment, the function in Fragment1()

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save near location
        outState.putParcelable(KEY_NEAR_LOCATION, mNearLocation);
        outState.putLong(KEY_SELECTED_TIME_IN_MILLIS, mSelectedTimeInMillis);


    }
like image 455
EyeQ Tech Avatar asked Mar 18 '15 07:03

EyeQ Tech


1 Answers

I know I'm late with response, but maybe it will help the others looking for answer to this question. When you have one activity with multiple fragments, onDestroy in fragment is not called. In result of this fragment is not destroyed as long as activity is not destroyed. But, when you replace fragment2 and you add it to backstack, then you come back to fragment1, in fragment2 will be called method onDestroyView. So, to save a state of fragment2 you need to do this inside onDestroyView, for example:

Bundle savedState;

public onCreateView(...){
 ..........
     if(savedState != null){
          String hello = savedState.getString("hello");
     }
 ..........
}
@Override
public void onDestroyView(){
     super.onDestroyView();
     savedState.putString("hello", "Say hello");
}

That's all. I hope it will help.

like image 54
Skye Avatar answered Sep 23 '22 22:09

Skye