cjayem13 cjayem13 - 1 year ago 64
Android Question

When to use getSharedPreferences vs savedInstanceState?

I'm trying to figure out when to use a saved instance state versus loading information from a shared preferences file. I have two variables that I wish to save, time and score. I want to make sure that if the user returns to the game screen that their score and time is saved and restored regardless if it's from onPause state or onStop.

I have three keys:

public static final String ARG_SCORE = "score";
public static final String ARG_TIME = "time";
public static final String SHARED_PREFS = "shared_preferences";


If the game is paused and a dialog is shown, when the user returns should I do

public void onRestoreInstanceState(Bundle savedInstanceState){
int score = savedInstanceState.getInt(ARG_SCORE);
}


or should I do something like:

protected void onResume(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt(getString(R.string.saved_high_score));
}


Overall, I need help understanding the lifecycle and when to store vital information such as time and score of the game. I simply need to avoid the user having to restart in cases they weren't able to finish the game.

Lastly, I'm assumed that the sharedPrefs saves to an xml file. Is this correct? Does anyone have a sample xml for how my sharedPrefs should appear? Do keys which are saved to bundles of savedInstanceState get stored in xml files as well? If so, any examples? If not, where is the information stored?

THANKS!




edits:

ok cool beans. Thanks! One more question, when defining a key for a key-value pair stored into sharedPreferences such as

public static final String ARG_SCORE = "score";


why is the "score" string stored? When would this ever be used? I've always placed a value into the key_value pair using something like

args.putInt(ARG_TIMER, timerINT);


and retrieved using

scoreINT=savedInstanceState.getInt(ARG_SCORE);


Why is a name needed for the key ARG_SCORE? When would I need the name? Does it have to stay type String?

Answer Source

use saveInstanceState when you are frequently moving back and forth between activities and use SharedPreferences when you want to keep information for long time and yes sharedpreferences stored in an xml file. you can view using DDMS in eclipse.

Remeber, in saveInstanceState, when you close app mean it get removes from memory, information will also lost. And in SharedPreferences, information will remain there if you close your app.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download