'when is onRestoreInstanceState called?

Sorry for my incomprehension, but I am new in the android development.

I have an application with activity A and activity B in it, and I go from activity A to activity B. When I left activity A, the onSaveInstanceState method was called, but when I went back to activity A (from activity B in the same application), the bundle in the onCreate method was null.

What can I do, to save the activity A's previous state? I only want to store the data for the application lifetime.

Can someone help me with this?

Here is my code for Activity A:

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

    if (savedInstanceState != null)
    {
        Log.v("Main", savedInstanceState.getString("test"));
    }
    else
    {
        Log.v("Main", "old instance");
    }
}  

@Override
public void onSaveInstanceState(Bundle savedInstanceState) 
{
    Log.v("Main", "save instance");

    savedInstanceState.putString("test", "my test string");

    super.onSaveInstanceState(savedInstanceState);
}


public void buttonClick(View view)
{
    Intent intent = new Intent(this, Activity2.class);
    startActivity(intent);
}

Here is my code for Activity B, when I press a button to go back to activity A:

public void onBack(View view)
{
    NavUtils.navigateUpFromSameTask(this);
}


Solution 1:[1]

To answer your question, have a look at the android doc: https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)

It says that onRestoreInstanceState is called after onStart() method in the activity lifecycle.

Solution 2:[2]

This happens because you are navigating the hard way. If you used the phone's default back button navigation, your onCreate would get the bundle passed in.

To circumvent this issue, I suggest you save your state to shared preferences as well as a back up. When the bundle is null, restore it from the shared preferences.

Solution 3:[3]

reference

onSaveInstanceState

... onPause()-> onSaveInstanceState() -> onStop() -> onDestory()

onRestoreInstanceState

onCreate()-> onStart()-> onRestoreInstanceState()-> onPostCreate(Bundle) ...

Or You can use LiveData. Save the states in it and observe.If the device rotates it'll update the views accordingly.

Solution 4:[4]

After onStart() which is after onCreate()

Solution 5:[5]

I used in this case a flag and SharedPreferences. This should work, and when you change the screen orientation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ranjithkumar
Solution 2 Ε Г И І И О
Solution 3 Makarand
Solution 4 bobbins
Solution 5 Vladimir Expert