When to use FragmentManager::putFragment and getFragment

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.

Leave a Comment