-1

I have an activity that has a container. And i have two fragments that I'm replacing into this container. The fragments are fragmentList and fragmentDetail

First time I'm adding the list fragment into the container

MainActivity OnCreate

 if (savedInstanceState == null) {
    ListFragment listFragment = new ListFragment();
    ft.add(R.id.fragment_container, listFragment, "LIST");
    ft.commit();
}

When the user clicks on the list, I replace the container with the detail fragment

ActionButton

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, detailFragment); 
fragmentTransaction.commit();

http://www.vogella.com/tutorials/Android/images/xfragmentsusage10.png.pagespeed.ic.MkyF4ZO5Hr.png

The problem came when I restart the activity. How I can know if I need to request the list data again, or if the detail fragment are shown? Because in my onResume method both fragments are null.

rafaelasguerra
  • 2,685
  • 5
  • 24
  • 56

2 Answers2

1

you are already checking the savedInstanceState which is your first step

check this document for details: http://developer.android.com/intl/es/training/basics/activity-lifecycle/recreating.html

the key is very simple, just save your current state in the onSaveInstanceState method, and restore the state on onRestoreInstanceState

the savedInstanceState is a bundle , Bundle objects are used to store and pass data between activities and fragments and so, you need to store a boolean variable in it to determine which fragment are you showing, and restore this fragment on resume according to this boolean flag

Hassan Khallouf
  • 1,170
  • 1
  • 13
  • 30
  • There another way to pass the 'activated fragment' instead passing a boolean? Because in my option, this should be deal in a clean way. – rafaelasguerra Mar 22 '16 at 18:27
  • you can't pass objects in your bundle unless they are parcables or Serializable , which is not possible or very difficult to do for fragments, besides it's the exact opposite of what u are supposed to do, Android deletes your fragment to free memory, if u store it, what is the point?!, if your fragment has info store them in the bundle as well, like strings and numbers, it's fairly easy and straight forward if that's what you mean by clean – Hassan Khallouf Mar 22 '16 at 18:32
  • do I have access to the bundle in onResume method? – rafaelasguerra Mar 22 '16 at 18:37
  • I'm not sure but I don't think so... override the 2 methods in the link .. one to save on to restore – Hassan Khallouf Mar 22 '16 at 19:03
0

You can use

getFragmentManager().FindFragmentByTag(string tag)

And check if it is null and then you can check isVisible on the fragment returned, generally you'll need to reset your adapters as well

Stampede10343
  • 844
  • 1
  • 6
  • 21