Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and fetch integer value in Shared Preference in android?

Tags:

android

I want to save and fetch the static integer value of Snow Density in Shared Preferences and change when user select another value in the Single choice.
My Code :

public static int mSnowDensity;
AlertDialog.Builder mABuilder = new AlertDialog.Builder(AAA.this);
final CharSequence mCharSequence[] = { "Low", "Medium", "High" };
mABuilder.setTitle("Set Density of Snow");
mABuilder.setSingleChoiceItems(mCharSequence,
        WallpaperServices.mDensitySnow,
        new android.content.DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                if (which == 2) {

                    mSnowDensity = 90;
             /*I Want to save mSnowDensity Value In Shared Preferences */
                } else if (which == 1) {

                     mSnowDensity = 60;
                } else {

                     mSnowDensity = 30;
                }

                dialog.dismiss();
            }
        });
like image 755
chotemotelog Avatar asked Dec 01 '22 18:12

chotemotelog


2 Answers

You can use shared preferences as follows

//To save
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("SNOW_DENSITY",mSnowDensity);
editor.commit();

//To retrieve
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("SNOW_DENSITY", 0); //0 is the default value

getSharedPreferences() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet. Else you should get the context using getApplicationContext() and then call getSharedPreferences() method.

For more options you can refer to the documentation at http://developer.android.com/guide/topics/data/data-storage.html#pref

like image 149
Sunil Mishra Avatar answered Dec 10 '22 11:12

Sunil Mishra


To save in the SharedPreferences:

private final String PREFS_NAME  = "filename";
private final String KEY_DENSITY    = "den";

Context  ctx   = getApplicationContext();
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putInt(KEY_DENSITY, mSnowDensity);
editor.commit();

To get the value:

Context ctx = getApplicationContext();
String strSavedValue = null;
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

strSavedValue = sharedPreferences.getInt("den", anyDefaultValue);
like image 45
g00dy Avatar answered Dec 10 '22 11:12

g00dy