Jimmy D
Jimmy D

Reputation: 5376

getLastNonConfigurationInstance()

Long story short, I have to develop a small application that displays a random image when the app launches. I discovered quickly that when the device orientation changed, the main activity re loaded and a new image was chosen. Someone on this site helped me solve this by declaring a null image outside of OnCreate(), and then inside of OnCreate() I have this:

image = (Bitmap) getLastNonConfigurationInstance();

    if (image == null) {
        image = getRandomImage();
    }
    setRandomImage(image);

This works nicely. My problem now is that I have to add a random "quote of the day" to the app and I can't make this work. A new quote is being pulled when the device orientation changes. I thought that maybe the following would work, but it doesn't:

message = (String) getLastNonConfigurationInstance();

    if (message == null) {
        message = getRandomMessage();
    }
    setRandomMessage(message);

I'm probably just not understanding how getLastNonConfigurationInstance() works, so if someone could help me out I'd appreciate it.

Upvotes: 1

Views: 9919

Answers (1)

Peter Knego
Peter Knego

Reputation: 80340

getLastNonConfigurationInstance() will give you Object that was returned by onRetainNonConfigurationInstance()

You can only save/retrieve one Object with this mechanism. So, just wrap both message and image in another class and use that.

Update:

public class ConfigWrapper{
    public Bitmap image;
    public String message;
}

then use it:

ConfigWrapper config = (ConfigWrapper) getLastNonConfigurationInstance();

if(config == null || config.image == null ){ 
    image = getRandomImage();
} else {
    image = config.image;
}
setRandomImage(image);

then create the config in your onRetainNonConfigurationInstance():

onRetainNonConfigurationInstance(){
     ConfigWrapper config = new ConfigWrapper();
     config.image = // get last image from where you have it
     config.message = // get last message 
     return config;
}

Upvotes: 11

Related Questions