How to save state in fragment

Wuttipong Khemphetjetsada picture Wuttipong Khemphetjetsada · Jun 11, 2017 · Viewed 15.7k times · Source

I have 4 button to replace fragment in activity [fragment A , fragment B , fragment C , fragment D] and then I replace fragment A to activity and I change value in fragment A after that I replace fragment B to fragment A and replace fragment C to fragment B . But I want to replace fragment A to fragment C . How to save state in fragment A.

Code when I commit fragment

  private void beginFragmentTransaction(BaseFragment fragment) {
    String tag = fragment.getClass().getName();
    currentFragmentTag = tag;

    boolean fragmentPopped = getChildFragmentManager().popBackStackImmediate(tag, 0);

    if (!fragmentPopped) {
        getChildFragmentManager().beginTransaction()
                .replace(R.id.container, fragment, tag)
                .addToBackStack(tag)
                .commit();
    }

}

Diagram to replace

fragment A -------> fragment B

fragment B -------> fragment C

fragment C -------> fragment A

PS. I don't want to use back button to back to fragment A , I want to replace fragment A and restore data in the first commit.

Answer

Sudheesh R picture Sudheesh R · Jun 11, 2017

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null.

FYI : this is a sample code. Just for your reference.

public class MainFragment extends Fragment {
private String title;
private double rating;
private int year;

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);

savedInstanceState.putString(TITLE, "Gladiator");
savedInstanceState.putDouble(RATING, 8.5);
savedInstanceState.putInt(YEAR, 2000);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

title = savedInstanceState.getString(TITLE);
rating = savedInstanceState.getDouble(RATING);
year = savedInstanceState.getInt(YEAR);
}
}

FYI : This really a good thread check this also Once for all, how to correctly save instance state of Fragments in back stack?