Retain the Fragment object while rotating - android

I have developed an app in Honeycomb and I am using fragments.
This is my app
I have an Activity (Say A1) and in that there is a fragment
Initially this fragment hold the object one fragment object say (F1)
Then depending on the user actions it may change to other objects F2,F3 ....
What my problem is
When The user rotate the device the activity is recreated and which make F1 as the fragment object even though before rotating it wasn't
What is the way to retain the fragment object while rotating?
I used setRetainInstance(true); but it didn't work for me
And I have added the fragment by code in my onCreate function like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment homeFragment = new Home();
fragmentTransaction.add(R.id.mainFragement, homeFragment);
fragmentTransaction.commit();
}

By default Android will retain the fragment objects. In your code you are setting the homeFragment in your onCreate function. That is why it is allways some homeFragment or fl what ever that you set in onCreate.
Because whenever you rotate, the onCreate will execute and set your fragment object to the first one
So the easy solution for you is check whether savedInstanceState bundle is null or not and set the fragment object
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(null == savedInstanceState) {
// set you initial fragment object
}
}

You need to give your Fragment a unique tag, and check whether this Fragment is already added to your Activity already or not.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String tag = "my_fragment";
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager.findFragmentByTag(tag) == null) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment homeFragment = new Home();
fragmentTransaction.add(R.id.mainFragement, homeFragment, tag);
fragmentTransaction.commit();
}
}
Checking whether savedInstanceState is null is not a safe way to check whether your fragment is already set - it will work in most cases, but in some cases (such as when the device is on low memory), Android may kill your Activity, which could break your application.
To see this in action, tick "Don't keep activities" in the device's development options (the setting is available in Android 4.0+, not sure about earlier versions). When you open a new activity, your first activity is destroyed. When you return to it (by pressing back), it is created again, and savedInstanceState is not null. However, your fragment is not in the activity anymore, and you have to add it again.
EDIT - Showing the original principle but with SupportFragmentManager
public class ActivityAwesome extends AppCompatActivity
{
private final String TAG = getClass().getSimpleName();
private FragmentHome mHomeFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(TAG);
if(fragment == null)
{
// Create the detail fragment and add it to the activity using a fragment transaction.
mHomeFragment = new FragmentHome();
fragmentManager.beginTransaction()
.add(R.id.fragment_container, mHomeFragment, TAG)
.commit();
}
else
{
// get our old fragment back !
mHomeFragment = (FragmentHome)fragment;
}
}
}
this comes in especially useful if you want to manipulate the fragment (in this case mHomeFragment) after rotating your device

Use onAttachFragment() in your Activity to reassign the object:
#Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof MyFragment)
this.myFragment = (MyFragment) fragment;
}

I defined a Fragment in activity's layout, onSaveInstanceState in the Fragment does get called, but the savedInstanceState Bundle in the Fragment's onCreatView comes as null.
The reason was that my Fragment did not have a ID in XML:
android:id="#+id/compass_fragment" ...

just rewiring #Ralf answer to be more dynamic, no need to specify a certain fragment to retain, but in case you want to specify, it is also possible :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set Home/Main/default fragment
changeFragmentTo(HomeFragment.newInstance(), FRAGMENT_TAG_HOME_FRAGMENT);
if (getCurrentFragment() != null) {
//if screen rotated retain Fragment
changeFragmentTo(getCurrentFragment(), getCurrentFragment().getTag());
}
}
private Fragment getCurrentFragment() {
//fl_main_container is FarmeLayout where I load my Fragments
return getSupportFragmentManager().findFragmentById(R.id
.fl_main_container);
}
/**
* changeFragmentTo(Fragment fragmentToLoad, String fragmentTag)
*
* #param fragmentToLoad : dataType > v4.app.Fragment :: the object of the fragment you want to load in form of MyFragment() or MyFragment().newInstance()
* #param fragmentTag : dataType > String :: a String which identify the "tag" of the fragment in form of "FRAGMENT_TAG_MY_FRAGMENT", Value must be stored in {#link models.MyConstants}
*/
public void changeFragmentTo(Fragment fragmentToLoad, String fragmentTag) {
if (getSupportFragmentManager().findFragmentByTag(fragmentTag) == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_main_container, fragmentToLoad, fragmentTag)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(fragmentTag)
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_main_container, fragmentToLoad, fragmentTag)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
}
}

You can simply set the RetainInstance property inside OnCreate of the fragment class.
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
RetainInstance = true;
}
Retain the Fragment object while rotating

Related

Why is onCreateView in Fragment called twice after device rotation in Android?

I have simple activity and fragment transaction. What i noticed that on configuration changes oncreateView of Fragment is called twice. Why is this happening?
Activity Code Here :
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Activity created");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
BlankFragment fragment = new BlankFragment();
addFragmentToActivity(manager,
fragment,
R.id.root_activity_create
);
}
public static void addFragmentToActivity (FragmentManager fragmentManager,
Fragment fragment,
int frameId)
{
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(frameId, fragment);
transaction.commit();
}
Fragment Code Here :
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
On first load onCreateView() is called once
But onRotation onCreateView() is called twice
why ?
Because of this transaction.replace(frameId, fragment); Really? Yes,I mean because of fragment .You already have one fragment onFirst load, When you rotate onCreate() will be called once again, so now fragment manager has old fragment ,so it methods will execute(once),and next you are doing transaction replace() which will remove old fragment and replace it with new once and again(onCreateView() will be called for second time). This is repeating for every rotation.
If you use transaction.add(frameId, fragment,UNIQUE_TAG_FOR_EVERY_TRANSACTION) you would know the reason. for every rotatation, no.of onCreateView() calls will increase by 1. that means you are adding fragments while not removing old ones.
But solution is to use old fragments.
in onCreate()of activity
val fragment = fragmentmanager.findFrgmentByTag("tag")
val newFragment : BlankFragment
if(fragment==null){
newFragment = BlankFragment()
}else{
newFragment = fragment as BlankFragment()
}
//use newFragment
Hope this solves confusion
Android automatically restores the state of its views after rotation. You don't have to call addFragmentToActivity again after rotation. The fragment will automatically be restored for you!
In your case, it happens twice because:
1. Android restores the fragment, its onCreateView is called
2. You replace the restored fragment with your own fragment, the oncreateview from that fragment is called too
do this:
if (savedInstanceState == null)
{
addFragmentToActivity(manager, fragment, R.id.test);
}

Retain multiple fragmens on screen rotation

First of all, I know that I can retain a single fragment with setRetainInstance(true); and retrieving from FragmentManager when savedInstanceState.
But my situation is that I have three fragments in my Activity, which I "swap" using transaction, depending on user actions.
I can also recreate the current fragment, saving the flag within onSaveInstanceState(Bundle savedInstanceState) to recover it when the user rotates the screen.
My problem comes when the user rotates the screen, being in one fragment and then click to go to previous fragment. Since the only fragment I can recover is the active fragment, I cannot show to the previous fragment without recreaing it (loosing all the information I had).
Here is my code. Also if this is not a good sollution, I would apreciate any tips.
private Fragment1 fragment1;
private Fragment2 fragment2;
private Fragment3 fragment3;
private String currentFragmentTAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight);
...
mFragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
// HOW TO RECOVER ALL FRAGMENTS??
fragment1 = ??;
fragment2 = ??;
fragment3 = ??;
String tag = savedInstanceState.getString(SAVED_FRAGMENT);
Fragment savedFragment = mFragmentManager.findFragmentByTag(tag);
replaceFragment(savedFragment, tag, null);
}
}
// Here, in other funcions, I initialize fragments and show one of them depending of user actions
// I use replaceFragment function to "swap" fragments.
private void replaceFragment(Fragment fragment, String tag, Map<String, Parcelable> objectsToBundle) {
if (fragment != null && !tag.equals(currentFragmentTAG)) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
if (objectsToBundle != null && !objectsToBundle.isEmpty()) {
Bundle bundle = new Bundle();
for (Map.Entry<String, Parcelable> entry : objectsToBundle.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
fragment.setArguments(bundle);
}
mFragmentTransaction.replace(R.id.fragment_weight_container, fragment, tag);
mFragmentTransaction.commit();
currentFragmentTAG = tag;
}
}
In my fragments I use setRetainInstance(true)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
Thank you so much!
The solution was quite simple. I just need to use FragmentTransaction.addToBackStack(tag) when perform the transaction in my replaceFragment function. This way all the fragments used in my activity will be retaines and could be recovered from FragmentManager
...
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.addToBackStack(tag);
...
So this is the way I can recover them (if already instantiated)
if (savedInstanceState != null) {
mWeightMainFragment = (WeightMainFragment) mFragmentManager.findFragmentByTag(WeightMainFragment.TAG);
mWeightAddFragment = (WeightAddFragment) mFragmentManager.findFragmentByTag(WeightAddFragment.TAG);
mWeightChartFragment = (WeightChartFragment) mFragmentManager.findFragmentByTag(WeightChartFragment.TAG);
currentFragmentTAG = savedInstanceState.getString(SAVED_FRAGMENT);
Fragment savedFragment = mFragmentManager.findFragmentByTag(currentFragmentTAG);
replaceFragment(savedFragment, currentFragmentTAG, null);
}
Bonus: I'm also using popBackStack() to undo transcactions instead of replace again with the back stack fragment.

Android Fragment created twice orientation change

My fragment is being created twice, even though the activity is only adding the fragment once to the content. This happens when I rotate the screen. Also, everytime the fragment's onCreateView is called, it has lost all of it's variable state.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) { // Checking for recreation
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AppPanelFragment())
.commit();
}
}
}
onCreate in the activity checks for the null savedInstanceState and only if null will add the fragment so I can't see why the fragment should be created twice? Putting a breakpoint in that if condition tells me that it only ever get's called once so the activity shouldn't be adding the fragment multiple times. However the onCreateView of the fragment still gets called each time orientation changes.
public class AppPanelFragment extends Fragment {
private TextView appNameText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This method called several times
View rootView = inflater.inflate(R.layout.fragment_app_panel, container, false);
// 2nd call on this method, appNameText is null, why?
appNameText = (TextView) rootView.findViewById(R.id.app_name);
appNameText.text = "My new App";
return view;
}
I managed to have the variable state persisted using setRetainInstance(true), but is this the real solution? I would expect the fragment to not be created on just an orientation change.
In android, when the phone's orientation is changed, the activity is destroyed and recreated. Now, i believe to fix your problem you can use the fragment manager to check to see if the fragment already exists in the back stack and if it doesn't then create it.
public void onCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mFragmentManager = getSupportFragmentManager();
AppPanelFragment fragment = (AppPanelFragment)mFragmentManager.findFragmentById(R.id.fagment_id);
if(fragment == null) {
//do your fragment creation
}
}
}
P.S. I haven't tested this but it should work once you provide the right fragment's id in the findFragmentById method.
The Fragment lifecycle is very similar to an Activity. By default, yes, they will be re-created during a configuration change just like an Activity does. That's expected behavior. Even with setRetainInstance(true) (which I would say to use with extreme caution if it contains a UI) your View will be destroyed and re-created, but in that case your Fragment instance will not be destroyed -- just the View.
I know it is a bit late to answer, but using The Code Pimp answer you can do the next thing:
If the fragment exists in the backstack we pop and remove it to add it back (an exception is thrown if it is added back without removing it, saying it already exists).
The fragment variable is a class member variable.
This method will be called in the onCreate method of the Activity:
if (savedInstanceState == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentById(getFragmentActivityLayoutContainerId()) == null) {
fragment = getNewFragmentInstance();
} else {
fragment = fragmentManager.findFragmentById(getFragmentActivityLayoutContainerId());
fragmentTransaction.remove(fragment);
fragmentManager.popBackStack();
fragmentTransaction.commit();
fragmentTransaction = fragmentManager.beginTransaction();
}
fragmentTransaction.add(getFragmentActivityLayoutContainerId(), fragment);
fragmentTransaction.commit();
}
The next code will be called in the fragment itself.
It is a small example for a code you could implement in your fragment to understand how it works. The dummyTV is a simple text view in the center of the fragment that receives text according to orientation (and for that we need a counter).
private TextView dummyTV;
private static int counter = 0;
#Override
protected int getFragmentLayoutId() {
return R.layout.fragment_alerts_view;
}
#Override
protected void saveReferences(View view) {
dummyTV = (TextView) view.findViewById(R.id.fragment_alerts_view_dummy_tv);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (savedInstanceState != null) {
dummyTV.setText(savedInstanceState.getString("dummy_string"));
} else {
dummyTV.setText("flip me!");
}
dummyTV.append(" | " + String.valueOf(counter));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("dummy_string", counter++ % 2 == 0 ? "landscape" : "portrait");
}
As mentioned, on orientation change, the activity is destroyed and recreated. Also, Fragments(any) are recreated by the system.
To ensure your application restores to previous state, onSaveInstanceState() is called before the activity is destroyed.
So, you can store some information in the onSaveInstanceState() method of an activity and then restore your application to same state on orientation change.
NOTE: You need not create fragments on orientation change, as fragments are recreated.
Example from http://www.mynewsfeed.x10.mx/articles/index.php?id=15:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState == null ){
//Initialize fragments
Fragment example_fragment = new ExampleFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container, example_fragment, "Example");
} else{
//control comes to this block only on orientation change.
int postion = savedInstanceState.getInt("position"); //You can retrieve any piece of data you've saved through onSaveInstanceState()
//finding fragments on orientation change
Fragment example_fragment = manager.findFragmentByTag("Example");
//update the fragment so that the application retains its state
example_fragment.setPosition(position); //This method is just an example
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position); //add any information you'd like to save and restore on orientation change.
}
}

Android retain Fragment not visible after orientation change

I try to reduce my view hierarchy and use the android.R.id.content view to add a Fragment which use setRetainInstance( true ) to keep its instance alive.
My activity is very simple
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate( final Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
// ensure that the view is available if we add the fragment
findViewById( android.R.id.content ).post( new Runnable(){
#Override
public void run() {
// add the fragment only once to manager
if( savedInstanceState == null ) {
getSupportFragmentManager()
.beginTransaction()
.add( android.R.id.content, new LoginFragment() )
.commit();
}
}
} );
}
}
The Fragment create its own view and use the setRetainInstance(true) method in onCreate().
My problem is that after a orientation change my fragment isn't re-added to the activity and the activity is empty.
savedInstanceState may not be null after you rotate screen, so fragment did not add to the activity.
Although the fragment itself do not get killed, but activity get killed and you have to re-add the fragment to activity again.
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentWithTag("TAG");
if(fragment == null){
fragment = new LoginFragment();
}else{
fm.beginTransaction()
.add(android.R.id.content, fragment, "TAG")
.commit();
}
By the way, setRetainInstance(true) is not meant to use this way. You should allow fragment to get kill and re-create along with activity.

Android - Viewpager and fragments, methods not working

I have a ViewPager with two Fragments which I instantiate in onCreate of my FragmentActivity.
private List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,Frag_1.class.getName()));
fragments.add(Fragment.instantiate(this,Frag_2.class.getName()));
this.vPagerAdapter = new Adapt(super.getSupportFragmentManager(),fragments);
vPager = (ViewPager) super.findViewById(R.id.pager);
vPager.setAdapter(vPagerAdapter);
My second Fragment has a method inside that I call to update my ListView - refreshList():
public class Frag_2 extends Fragment {
private ListView list;
private ArrayList<data> data;
private boolean firstCreation=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(false);
}
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, container, false);
list = (ListView) view.findViewById(R.id.lst);
//this.setRetainInstance(true);
return view;
}
public void refreshList(ArrayList <data> data){
if(data!=null){
ArrayAdapter<data> adapter = new Item_data_adapter(getActivity(),data);
list.setAdapter(adapter);}
}
}
Called from my FragmentActivity
//Something
Frag_2 fr = (Frag_2) vPagerAdapter.getItem(1);
if (fr.getView() != null) {
fr.refreshList(data);
}
It works fine until I change the orientation of the screen. Correct me if I'm wrong, but I was searching for hours and I didn't find a solution or a good explanation, the FragmentActivity is created only one time and the Fragments are attached to it but the Fragments recreate on configuration changes.
Now, when the orientation changes I don't get the View from onCreateso when I try to get the View from the Fragment it returns null and my refreshList() method isn't called. How can I fix this?
I fixed the problem this way:
In the onCreate of the FragmentActivity
if(savedInstanceState!=null){
frag1 = (frag_1) getSupportFragmentManager().getFragment(savedInstanceState, frag_1.class.getName());
frag2 = (frag_2) getSupportFragmentManager().getFragment(savedInstanceState, frag_2.class.getName());
}
else{
frag1 = (frag_1) Fragment.instantiate(this,frag_1.class.getName());
frag2 = (frag_2) Fragment.instantiate(this,frag_2.class.getName());
}
fragments.add(frag1);
fragments.add(frag2);
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, frag_1.class.getName(), frag1);
getSupportFragmentManager().putFragment(outState, frag_2.class.getName(), frag2);
}
Maybe it's not the best solution in the universe, but it looks like it works...
When u want to refresh the List do something like this :
public void setView() {
Frag_2 fr = (Frag_2) vPagerAdapter.getItem(1);
fragmentManager.beginTransaction().detach(fr).commit();
fragmentManager.beginTransaction().attach(fr).commit();
}
If you are using a dynamic fragment, you need to test first to prevent creating a second instance of a fragment.
To test whether the system is re-creating the activity, check whether the Bundle argument passed to your activity’s
onCreate() is null.
If it is non-null, the system is re-creating the activity. In this case, the activity automatically re-instantiates existing
fragments.
If it's null you can safely instantiate your dynamic fragment. For example:
public void onCreate(Bundle savedInstanceState) {
// ...
if (savedInstanceState != null) {
FragmentManager fragmentManager = getFragmentManager()
// Or: FragmentManager fragmentManager = getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
The Fragment class supports the onSaveInstanceState(Bundle) method (but not the onRestoreInstanceState() method) in much the same way as the Activity class.
The default implementation saves the state of all the fragment’s views that have IDs.
You can override this method to store additional fragment state information.
If the system is re-creating the fragment from a previous saved state, it provides a reference to the Bundle containing that state to the onCreate(), onCreateView(), and onActivityCreated() methods; otherwise, the
argument is set to null.
If you want a detailed info, here's a good talk by Ken Jones of Marakana

Categories

Resources