How to restore the state of the previous activity when the arrow is pressed

advertisements

I have a activity Home which has a fragment. I am trying to restore the state of activity when user come back to Home.

That's the method of Home Activity which store the instance of fragment to Bundle

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    getSupportFragmentManager().putFragment(outState,"fragment",feedFragment);
}

And i have this check onCreate in HomeActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    context = this;
    initUi();
    initToolbar();
    initFragment(savedInstanceState);
}

private void initFragment(Bundle savedInstanceState) {

    if(savedInstanceState!=null){
        feedFragment = getSupportFragmentManager().getFragment(savedInstanceState,"fragment");

    }else{
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.content_container, feedFragment).commit();
    }
}

So the problem is when i change orientation of screen when i am in HomeActivity. It restore it states. But when i am in some other activity and i come back to home activity from Back arrow in actionbar of another activity. then it doesn't restore it states it start loading data from server again. What am i doing wrong? how can i restore the prevoius state when i navigate back to HomeActivity from Back arrow in action bar


You mus use onSaveInstanceState and onRestoreInstanceState methods. Read this answer so you can find a solution to your problem.