简体   繁体   中英

Android and onSaveInstance and Restore

I have a big problem. I have a activity where I have two imageViews. In onCreate I have List pictures where I have 10 pictures. Every time when I start this activity both imageViews get random picture from List and shows them. For example: When I start activity I can see car and pencil and when I start this activity once again I get elephant and book. Now this is my problem. When I start activity and block my phone and after that unlock I get other pictures. I think that onCreate is called again. I create

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

public void onRestoreInstanceState(Bundle savedInstanceState) {

    if  (savedInstanceState != null) {
        pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair().getImageLeft()));
        pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair().getImageRight()));         
    }   
}

pictureGameLeft and Right that is last images which is shows. I write them after onCreate method. How I can save last seen picture that if I lock and unlock phone I get the same pictures. Maybe onPause or onStop need called?

edit: now:

if (savedInstanceState == null) {
    game = new Game();
    game.initGame();
    addElements(result);

    game.getCurrentLevel().nextPair();

    pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
        .getImageLeft()));
    pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
        .getImageRight()));

    mRedrawHandler.sleep(1000);             
} 
else {
    pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair(
        .getImageLeft()));
    pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
        .getImageRight()));
}

but I get NullPointerException.

I would save the current choice of pictures into the preferences at the very moment the decision is taken. Than you don't have to fiddle with the live cycle methods.

The decision when to take the choice from preference or to create a new (random) choice is easy. Just check whether

savedInstanceState

of

public void onCreate (Bundle savedInstanceState)

is null. If so, it is the first call. Subsequent reopen have a non-null value

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