Android - Save current onCreate state when switching between different activities

585 Views Asked by At

I am new to java and android studio and after reading documentation I am still a little confused with the activity lifecycle and how to use it effectively.

I am building an application which has several activities. There is key data loaded in when the app is first opened in the main activity. However when I move to another activity and then back to the main, the onCreate is invoked again which I do not want. I am aware there is a way to save the instance of your onCreate but I am still unsure of how to do this. Here is what I have done:

 @Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    if (outState != null) {
        // Restore value of members from saved state
        outState.putString("step_count", String.valueOf(stepCount));
        outState.putString("cal_count", String.valueOf(calCount));
        outState.putString("dis_count", String.valueOf(disCount));
        android.util.Log.d(TAG, "onSaveInstanceState");

    } else {
        // Probably initialize members with default values for a new instance
    }

}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    savedInstanceState.getString("step_count", String.valueOf(stepCount));
    savedInstanceState.getString("cal_count", String.valueOf(calCount));
    savedInstanceState.getString("dis_count", String.valueOf(disCount));
    stepCount.setText(String.valueOf(stepCount));
    calCount.setText(String.valueOf(calCount));
    disCount.setText(String.valueOf(disCount));
    android.util.Log.d(TAG, "onRestoreInstanceState");

}

Would appreciate any sort of support and guidance. Thank you.

1

There are 1 best solutions below

2
On

Again - not a simple question.

First of all: Yes, you can save data "from last session" by overriding: onSaveInstanceState() and restore it overriding onRestoreInstanceState(savedInstanceState: Bundle?). Look here: https://developer.android.com/guide/components/activities/activity-lifecycle#saras

Second of all: According to your description it seems that you need SharedPreferences more than this. If you need a key to anything and it should be used from opening of the app until it is killed or user is logged out, SharedPreferences are the most common solution.

onSaveinstanceState() was created to make possibility to remember what was on the screen "in the last session" without "calculating" it again. For example EditText.text or ImageView.url or similar.