Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem saving shared preferences in Android

Right now I am trying to save a variable when i close the app and get the variable back when i open the app back up. I have no idea if I'm doing this right. My variable is called count and would like to save and restore it. Is this right? If so, why isn't it working? If not, what do i need to change? (i'm obviously using SharedPreferences)

protected void onPause(){
   super.onPause();


  SharedPreferences settings = getSharedPreferences(PREFS_COUNT, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInt("count", count);
  editor.commit();
}
@Override
protected void onResume(){
    super.onResume();
    SharedPreferences settings = getSharedPreferences(PREFS_COUNT, 0);
    count = settings.getInt("count", count);
}
like image 988
Keenan Thompson Avatar asked Oct 16 '10 02:10

Keenan Thompson


People also ask

How do you save data using the shared preferences object?

You can create a new shared preference file or access an existing one by calling one of these methods: getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.

Where shared preferences are stored in Android device?

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .

What can I store in shared preferences?

Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.


1 Answers

Looks right except make sure you have a constant:

public static final String PREFS_COUNT = "MyPrefsFile";

declared at the beginning of your activity. It's all right here in Google's documentation:

http://developer.android.com/guide/topics/data/data-storage.html#pref

Should work fine if you follow that exactly.

like image 63
ShadowGod Avatar answered Dec 01 '22 01:12

ShadowGod