简体   繁体   中英

Why does my Android onRestoreInstanceState method never get called eventough I save the activity state?

I have a surface view gameView, which gets loaded in this GameViewActivity.
I save a few values in the onSaveInstanceState method. And when I leave this activity and come back the OnCreate() gets called again, reverting my activity back to its original state and the onRestoreInstanceState never gets called.

On top of that, when I check the Bundle that gets passed into the OnCreate method its always null. Any idea, im very much stuck here?

public class GameViewActivity extends AppCompatActivity {


private int player;

private GridView grid1;
private GridView grid2;

private GameView gameView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    try {
        grid1 = new GridView(Constants.NUMBER_COLUMN_TILES, Constants.NUMBER_ROW_TILES);
        grid2 = new GridView(Constants.NUMBER_COLUMN_TILES, Constants.NUMBER_ROW_TILES);
    } catch(Exception e){
        e.printStackTrace();
    }

    this.player = 1;
    gameView = new GameView(this, "sea", grid1);

    setContentView(gameView);

}



@Override
protected void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putSerializable("tiles_player1", grid1.getTiles());
    outState.putSerializable("tiles_player2", grid2.getTiles());
    outState.putInt("player", player);

}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    grid1.setTiles((HashMap<Coordinate,GameTile>) savedInstanceState.get("tiles_player1"));
    grid2.setTiles((HashMap<Coordinate,GameTile>) savedInstanceState.get("tiles_player2"));

    player = (int)savedInstanceState.get("player");
}

onSaveInstance/onRestoreInstance are designed to store the activity state only when system kills it (eg low memory when app is in background). So if you leave the activity by navigating back (eg by pressing the Back button) - it is not going to call onSaveInstanceState and then onRestoreInstanceState when you open activity again. Instead you should persist activity data in SharedPreferences or sqlite or file (let's say in onStop() method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM