OrdinaryProgrammer
OrdinaryProgrammer

Reputation: 11

Recreating activity state after clicking back button

I can't find out why savedInstanceState is always null in the onCreate method when I'm successfully saving data to the Bundle in onSaveInstanceState method. When I'm running my program on AVD and clicking back button(destroying activity) and then creating it again by clicking its icon the saved state is always null. Here is a simple program which tests this problem.

package com.example.myTestApp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button)findViewById(R.id.button);
        if(savedInstanceState == null){
            button.setText("No");
        }else{
            button.setText("Yes");
        }
    }

    static final String STATE_SCORE = "playerScore";
    static final String STATE_LEVEL = "playerLevel";
    private int mCurrentScore = 1;
    private int mCurrentLevel = 2;


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

        savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
        savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    }
}

Tell me how to solve this problem if possible.

Upvotes: 1

Views: 446

Answers (1)

Francesc
Francesc

Reputation: 29260

That is expected. When you press back, the Activity is destroyed and the data it had is lost. After this you will always get null in the bundle as a new, fresh instance is being created when you reopen the app.

The Bundle savedInstanceState is used when the activity is being recreated due to some changes (like rotation), or because it was paused in the background for a long time.

If you want to persist some data, consider SharedPreferences for small stuff, or maybe a database (SQLite, Realm) or files for large stuff.

Upvotes: 2

Related Questions