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();
}
});
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With