Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
cjayem13 Avatar asked Jul 18 '14 09:07

cjayem13


1 Answers

You usually want to use SharedPreferences when you want to persist some information between different app session. Imagine you want to store information that you want to retrieve also after the user closes the app.

SavedInstanceState is used to keep some information while user is using the app and allow you to track temporary state of your activity or fragments.

Hope it helps.

like image 148
AlexBalo Avatar answered Sep 18 '22 12:09

AlexBalo