When to use FragmentManager::putFragment and getFragment
I've got an application that uses fragments and I was playing around with how to use the same fragment in an Activity with a dual pane and an Activity as a stand alone. Still not sure on the best method for completing this but I noticed the FragmentManager has a putFragment and getFragment function. What confuses me is that you have to provide a Bundle as parameter to both get and put functions. How can separate Activities have the same Bundle? Obviously you could pass the Bundle as a parameter but at that point I feel like you're just making a mess of things.
So what is a good scenario for using getFragment and putFragment? Please include the Bundle parameter explanation.
The basic answer:
These are only useful when implementing onSaveInstanceState() and restoring that state in onCreate(). If you are not implementing onSaveInstanceState(), you can forget about these methods and pretend like they don't exist.
The problem they are solving: if you want to save a reference to a fragment in your "saved instance state," you can't just put an object reference in there. First because well you can't put plain object in a Bundle. :) And the reason for this is that the point of that saved state is for it to be copied out of your process, so if your process needs to be killed, it can later be copied back in to a new process for you to re-initialize your activity/fragment from. A raw object is only meaningful in the context of the process it is running in, so it isn't possible to correctly copy the reference to such an object out of your current process and in to another.
So what putFragment()/getFragment() do is place a piece of data in the given Bundle that can identify that fragment across to a new instance of your activity/fragment in another process. Exactly what this representation is, is not defined, but in the current implementation it is the internal integer identifier for that fragment, which will be used later when the FragmentManager needs to re-create that fragment from a previously saved state... it is re-created with that same identifier, so when you then call getFragment() it can retrieve the integer, and use that to determine the correct Fragment object to return to the caller that corresponds to the one that was previously saved.
In short, It is just the way that you can retrieve reference of fragment after Activity
is restored. For instance, when you create a fragment and use it throughout your activity, so after configuration change, your activity is recreated, you want that reference back. So
public void onSaveInstanceState(Bundle outState){
getFragmentManager().putFragment(outState,"myfragment",myfragment);
}
public void onRetoreInstanceState(Bundle inState){
myFragment = getFragmentManager().getFragment(inState,"myfragment");
}