Reputation: 33901
I've got a retained fragment that works fine when rotating the screen (after call to the parent application's onCreate()).
However as soon as I leave the application and return to it (for example by going to the home screen and then returning to my app), the fragment does not seem to behave correctly.
So essentially what is happening is that each time I 'return' to my Activity the fragment within seems to be 'reset' in some way. Is this something to do with fragment transactions potentially?
On the last call to Log.d() the gameFragment.testValue is returning null - how does this occur? The only place I set the value is through the earlier condition block. How would the fragment be created without that value being set?
gameFragment = (GameFragment)fragmentManager.findFragmentByTag("gameFragment");
if (gameFragment == null)
{
gameFragment = new GameFragment();
gameFragment.setRetainInstance(true);
gameFragment.testValue = new Random().nextInt(1000);
Log.d("hmm", " after set test value:" +gameFragment.testValue);
fragmentManager.beginTransaction().add(gameFragment, "gameFragment").commit();
fragmentManager.executePendingTransactions();
gameFragment.testValue = new Random().nextInt(1000);
Log.d("hmm", " after commit, after set test value:" +gameFragment.testValue);
}
else
{
Log.d("hmm", "test value:" +gameFragment.testValue);
}
Upvotes: 0
Views: 76
Reputation: 1334
Checking the documentation you will find
All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
Consider setting up the parameters through setArguments
method and bundle - this way, when Android recreates the Fragment it will be able to set the params to old values.
Something to support the thesis: http://developer.android.com/reference/android/app/Fragment.html#setArguments(android.os.Bundle)
Upvotes: 2
Reputation: 1006734
On the last call to Log.d() the gameFragment.testValue is returning null - how does this occur?
One possibility would be that your process had been terminated. Android will recreate your fragments using the zero-argument public constructor, and it will give you your savedInstanceState
Bundle
. But the "retain" part of a "retained fragment" is only for configuration changes, so anything retained solely by that means will be lost.
Upvotes: 1