Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android restore instance state of a fragment that is in backstack

Hi I have an activity that has two fragments.

  1. Fragment A
  2. Fragment B

    • Fragment A has an EditText and a ListView.
    • Once I enter something in the EditText and hit Enter, I populate the ListView.
    • Now Fragment A's ListView is populated with data.
    • Clicking any item on the ListView of fragment A will send the user to fragment B
    • At this point I am replacing fragment A with fragment B
    • So when the user hits back button he comes back to fragment A

Now the problem is if the user is in fragment B and config changes occur like screen rotation etc more than once then my that my ListView is empty because my arraylist is null.

Note that I am using onSavedInstanceState in fragment A and fragment B. If my current fragment is fragment A and config changes occur then there is no problem of restoring the state since in onCreateView I am getting the arraylist from bundle.

I know the reason why my arraylist is null when I comeback from fragment B to fragment A which is in backstack previously.When fragment A is in backstack the only method that is being called is onSaveInstanceState so after the first config change my arraylist field is null as I couldnt assign my arraylist stored in savedInstateState bundle to the arraylist field.

I do not want to use android:configchanges attribute in my manifest.

My Question is how can I restore the state of a fragment that is in backstack.

like image 643
krishna Avatar asked Jun 05 '15 05:06

krishna


1 Answers

I achieved the goal of retaining the state of fragment which is in backstack by passing all the details of that fragment to main activity before it is added to backstack and saving the state in main activity's savedInstance state and whenever backstack changes and previous fragment is visible I am passing the saved instance state of that fragment to it from main activity and this way I am retaining the state. I am not sure if this the right approach.

like image 61
krishna Avatar answered Sep 25 '22 13:09

krishna