Michael
Michael

Reputation: 648

Alternatives to using onRetainNonConfigurationInstance

I have an app that potentially tracks a large amount of data during app use for a single player, and my app can allow up to 5 players at a time, which means this large amount of data is potentially multiplied times 5.

I write all of the data to my SQLite database when the Activity is destroyed, and this works fine.

The problem occurs during an orientation change. I used onRetainNonConfigurationInstance because I thought that I could at least rely on it for orientation changes, but what I have found is that other things going on within Android can wipe out my data. Some examples reported by users:

- While the app was running, the user took a phone call. After returning to the app, the data was gone.
- While the app was running, another user downloaded an update to a different app from the Market, and found the data gone after returning to the app.
- While the app was running, another user started a different app (a music player), and returned to find the data gone.

I know that the use of onRetainNonConfigurationInstance is the problem because my app initially wrote each individual data field for each player to a bundle, and while the app was implemented that way, no problems were encountered over the course of many months.

As soon as I found out about onRetainNonConfigurationInstance and used that for my implementation, I started receiving complaints.

My implementation is simple. I implement as follows:

@Override
public Object onRetainNonConfigurationInstance()
{
    return mPlayers;  //array of player objects
}

Then in onCreate, I do this:

mPlayers = (PlayerData [])getLastNonConfigurationInstance();

Since there appears to be some underlying problem, what is the best alternative for retaining large amounts of user data across screen rotations?

Thanks for any assistance!

Upvotes: 4

Views: 3019

Answers (2)

JiajiaGu
JiajiaGu

Reputation: 1339

Create a Fragment with setRetainInstance(true), write your fields that need to retain in it and add to Activity.

private PlayerData[] mPlayerDataArr;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

public void setPlayerDataArr(PlayerData[] playerDataArr){
    this.mPlayerDataArr = playerDataArr;
}

public PlayerData[] getPlayerDataArr() {
    return mPlayerDataArr;
}

Upvotes: 0

Femi
Femi

Reputation: 64700

Use the Bundle: the problem with onRetainNonConfigurationInstance is that it is tied to the lifecycle of the app's process, while the Bundle can be saved and restored even if the process is completely killed.

If you are going to have folks going off and doing memory-intensive things that might result in the process getting killed then go with the Bundle.

Upvotes: 4

Related Questions