4

I am using Fragments in my app project. All the fragments are added to back stack:

...
fragmentTransaction.addToBackStack(null);
...

Later on, what is the correct way to get all fragments from back stack in order ?

a.ch.
  • 8,285
  • 5
  • 40
  • 53
Leem.fin
  • 40,781
  • 83
  • 202
  • 354

1 Answers1

4

Using the getBackStackEntryCount() you can iterate through the back stack and use the getBackStackEntryAt() method to get each Fragment.

EDIT: Based on some discussions in the comments, it is advised that you manually store a list of the Fragments you have added to your backstack, and persist these into your SharedPreferences. You can then read this list back when the application starts, and reload these fragments.

Mimminito
  • 2,803
  • 3
  • 21
  • 27
  • 3
    But I got "BackStackEntry" when call getBackStackEntryAt(), how can I get fragment? I need fragments in back stack. – Leem.fin Mar 19 '12 at 15:39
  • Apologies, it looks like you are not able to use those Methods. You will need to manually keep a reference yourself, although the documentation for the BackStackEntry does state you should not hold onto these references. http://developer.android.com/reference/android/app/FragmentManager.BackStackEntry.html – Mimminito Mar 19 '12 at 15:42
  • May I ask what you are trying to achieve? There may be a better solution – Mimminito Mar 19 '12 at 15:42
  • My app will be killed when the server response is not correct. If user launch the app again, my app should show the previously displayed fragment, so my app need to persist the fragments back stack information locally, I need to get the fragments from backstack in order. – Leem.fin Mar 19 '12 at 15:44
  • 1
    You should manually store a list of all the fragments you currently have open. If you know when the application is going to be killed, then you will be able to persist the list into the SharedPreferences and then retrieve them when the app starts again. Everytime you add or remove something to the back stack, make sure you add the reference into your list. To make it simpler, have a Constants class which assign each fragment an ID (of type int) and you will then be able to cross reference which Fragment it is you have loaded. – Mimminito Mar 19 '12 at 15:47
  • Ok, because each of my fragment has a tag, I plan to use List to store the tag of fragment every time a fragment is put on stack. Then persist the list in SharePreferences. Could you make an answer, and I can accept it _ – Leem.fin Mar 19 '12 at 15:49