Android Fragment Onrestoreinstancestate

android fragment onRestoreInstanceState

Fragments do not have an onRestoreInstanceState method.

You can achieve the same result in onActivityCreated, which receives a bundle with the saved instance state (or null).

Check the source code here.

Execute operation from fragment after onRestoreInstanceState

The easy fix should be posting the init() step after cardHelper has been laid out, therefore onRestoreInstanceState has already been called. To do that you just have to perform init() in post(...):

cardHelper.post(new Runnable() {
public void run() {
cardHelper.init();
}
});

Haven't tested it, I assume it will work.

Saving and restoring state using fragments

You want to save the value of your current checked state in onSaveInstanceState.

Something like this:

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(CHECK_BOX_STATE, cb.getChecked());
}

and then when your view is created you want to get the value if it's present. And set your CheckBox state with it.

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fifth_layout, container, false);

cb = (CheckBox) view.findViewById(R.id.checkBox);
if (savedInstanceState != null) {
// Restore last state for checked position.
boolean checked = savedInstanceState.getBoolean(CHECK_BOX_STATE, false);
cb.setChecked(checked);
}

return view;
}

EDIT:

When you add the fragment, make sure to add it with a tag or id so that you can retrieve the same instance.

You could do a helper method to retrieve fragment and set the fragment.

private void setFragment(String tag, Fragment newFragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment savedFragment = fm.getFragmentByTag(tag);
fm.replace(R.id.container, savedFragment != null ? savedFragment : newFragment, tag);
fm.commit();
}

so you your switch you can call the helper method instead.

switch (position) {
case 0:
setFragment("A", new FragmentA());
break;
....
}

Note: This is just an example not best practice since you are creating new fragments every time in your switch case now anyways. But it might point you in the right direction.

How to use onSaveInstanceState and onRestoreInstanceState methods with fragments?

You will want to override the onSaveInstanceState method of your activity so that you know when the state needs to be saved. Then you will also need to update your onCreate method to check if the savedInstanceState is null. If it is null then the activity hasn't been initiated. This is the example for your MainActivity class, and you can go from there:

MainActivity.java

public class MainActivity extends Activity implements AddToDoFragment.OnToDoAddedListener {

private ArrayList<String> todoItems;
private ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if(savedInstanceState == null) {
todoItems = new ArrayList<String>();
} else {
todoItems = savedInstanceState.getStringArrayList("todoItemTag");//the tag must match what the variable was saved with
}

FragmentManager fm = getFragmentManager();

ToDoListFragment listToDo = new ToDoListFragment();
listToDo = (ToDoListFragment) fm.findFragmentById(R.id.list_view_fragment);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
listToDo.setListAdapter(adapter);
}

public void OnToDoAdded(String newToDo) {
todoItems.add(newToDo);
adapter.notifyDataSetChanged();

}

//Saving the instance by overriding this function
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

outState.putStringArrayList("todoItemTag", todoItems);//it would be advised to make the tags a static final String
}

Hopefully this helps!

PS: I don't think the onRestoreInstanceState method is really necessary. I guess I have never used it before. I believe that you should be able to provide the same functionality with the null check in the onCreate method.

View.onRestoreInstanceState not being called when fragment setRetainInstance(true) (double screen orientation change when fragment is in a back stack)

So, I've finished implementing save/restore logic manually.
The minus is that I can't turn off save\restore that already exist, so onSaveInstance/onRestoreInstance is called twice on a View. Except of that one time when it is not called by itself - then it IS called once B-).

To make it work just add to Fragment1 class:

    SparseArray<Parcelable> savedState;

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

if (savedState != null)
view.restoreHierarchyState(savedState);
}

@Override
public void onDestroyView() {
super.onDestroyView();
savedState = new SparseArray<Parcelable>();
getView().saveHierarchyState(savedState);
}

How do I restore the previous RecyclerView state when a fragment is recreated?

Farid correctly says in the comment: These methods are used in cases when the Activity is destroyed, for example, when there is a lack of memory or when the configuration is changed (screen rotation and others). If you just clicked the Back button and thereby explicitly closed the Activity yourself, then these methods will not be executed.

If you want to have data after closing the application, then you must save this data to persistent memory.
The Preference Library is suitable for storing the simplest variables.
If the data structure is complex, then it is better to use Database.

How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following:

1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

//Save the fragment's state here
}

}

2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

class MyActivity extends Activity {

private MyFragment

public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}

}


Related Topics



Leave a reply



Submit