How to save and fetch integer value in Shared Preference in android? - 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();
}
});

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);

Save the value in prefrence
private void SavePreferences(String key, int value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
get the value from preference
private void showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int savedPref = sharedPreferences.getInt(key, 0);
}
You can use the key as the shared preference name

Initialization
We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 :- for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true);
editor.putString("key_name", "string value");
editor.putInt("key_name", "int value");
editor.putFloat("key_name", "float value");
editor.putLong("key_name", "long value");
editor.commit();
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

Saving preference is not a troubling task. But if you have a lot of such configurable options you could use a PreferenceActivity and override onSharedPreferenceChanged.
More details here http://developer.android.com/guide/topics/ui/settings.html

Related

I am trying to pass the values in shared preference from one Activity to another

I am trying to pass the values from one activity to another using shared preference but am getting null value.In the first activity i printed values in console and its getting printed but in that i couldn't retrieve the values.please help me to come out of this error
First activity: values are passed
sharedpreferences.edit().putString("CHECKPASS","changepass").commit();
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
Second Activity: where I am retrieving
Log.d("succ", "reached");
String yourpass = sharedpreferences.getString("CHECKPASS","changepass");
Log.d("succ", "yournext" + yourpass);
if (yourpass.equals("changepass")) {
{
final String foodshared = sharedpreferences.getString("FOOD","NULL");
Log.d("succ", "foodshared" + foodshared);
final String colorshared = sharedpreferences.getString("COLOR", "NULL");
Log.d("succ", "colorshared" + colorshared);
final String buyshared = sharedpreferences.getString("BUY", "NULL");
Log.d("succ", "buyshared" + buyshared);
final String placeshared = sharedpreferences.getString("PLACE", "NULL");
Log.d("succ", "placeshared" + placeshared);
}
Use this code
//For writing data
SharedPreferences.Editor
editor=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE).edit();
editor.putString("CHECKPASS","changepass");
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.apply();
//For Reading Data
SharedPreferences sharedPreferences=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE);
String foodshared = sharedPreferences.getString("FOOD","NULL");
String colorshared = sharedPreferences.getString("COLOR", "NULL");
final String buyshared = sharedPreferences.getString("BUY", "NULL");
final String placeshared = sharedPreferences.getString("PLACE", "NULL");
Also while writing data don't use editor.commit() instead use editor.apply() because it handles data in background.
UPDATE:
in your first activity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);//or MODE_PRIVATE
Editor editor = pref.edit();
editor.putString("CHECKPASS","changepass")
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
IN your secondActivity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
final String foodshared = pref.getString("FOOD",null);
Log.d("succ", "foodshared" + foodshared);
final String colorshared = pref.getString("COLOR",null);
Log.d("succ", "colorshared" + colorshared);
final String buyshared = pref.getString("BUY",null);
Log.d("succ", "buyshared" + buyshared);
final String placeshared = pref.getString("PLACE",null);
Log.d("succ", "placeshared" + placeshared);
edit:
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
STORE THE DATA
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getBoolean("key_name", null); // getting boolean

How to change value of a string?

String stored contains "1.0" in it. and I want to increase its value by 0.5, every time I press the button. But instead, my output becomes "1.00.5". How do I fix this?
String stored = userspeed.getText().toString();
String speedplus = stored + 0.5;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
UPDATE
public class ProgramActivity extends AppCompatActivity {
EditText userspeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
userspeed = (EditText) findViewById(R.id.userspeed);
//load values
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String stored = preferences.getString("user_speed", "1.0");//default
userspeed.setText(stored, TextView.BufferType.EDITABLE);
}
public void adduserspeed(View view) {
String stored = userspeed.getText().toString();
double storedValue = Double.parseDouble(stored);
String speedplus = String.valueOf(storedValue +0.5f);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
}
}
First, you need to convert your string value to a float value, then perfom the add operation and finally convert the result to a string so you can store as a string in shared preferences.
final String stored = userspeed.getText().toString();
final float storedValue = Float.parseFloat(stored);
final String speedplus = String.valueOf(storedValue + 0.5f);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
If you want to use a double value, simply replace first lines as the follows:
final String stored = "1.0";
final double storedValue = Double.parseDouble(stored);
final String speedplus = String.valueOf(storedValue + 0.5d);
UPDATE
Your problem is that within adduserspeed(View view) method your are not retrieving the stored value from preferences, your are retrieving from the EditText, and you are not updating that EditText value, so every time you execute adduserspeed(View view) method, the value you are storing on preferences is 1.0 + 0.5, because you EditText value is 1.0 until you re-open your app. When you re-open your app your EditText value is 1.5 and so on...
I have improved your code and now works well, anyway, do not just copy my code, try to understand it so you can learn.
public class MainActivity extends AppCompatActivity {
private EditText userSpeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.userSpeed = (EditText) findViewById(R.id.userspeed);
setUserSpeedText();
}
public void adduserspeed(View view) {
final String stored = getUserSpeedValue();
final double storedValue = Double.parseDouble(stored);
final String speedPlus = String.valueOf(storedValue + 0.5f);
setUserSpeedValue(speedPlus);
setUserSpeedText();
}
private String getUserSpeedValue() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString("user_speed", "1.0");
}
private void setUserSpeedValue(final String newSpeedValue) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", newSpeedValue);
editor.apply();
}
private void setUserSpeedText() {
if (null != this.userSpeed) {
this.userSpeed.setText(getUserSpeedValue());
}
}
}
You can also use double like:
String speedplus = (Double.parseDouble(stored)+0.5).toString();
Try parsing stored i.e. 1.0 as Double and then add 0.5d
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
Final code
String stored = userspeed.getText().toString();
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
String stored = userspeed.getText().toString();
float speedplus = Float.parseFloat(stored) + 0.5;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("user_speed", speedplus);
editor.apply();
Parse the string value to int and then do mathematical operation. Otherwise string concatenation will happen.
The quickest hack would be:
String speedplus = String.valueOf(Float.parseFloat(stored) + 0.5F);
However, your next question will no doubt be "Why is my result 1.499999999?", which is answered here in detail.

Android Shared Preferences don't Save Properly

I am trying to use Android Shared Preferences to save certain app values
Here is the code of my onCreate:
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = getSharedPreferences("MyPref", MODE_PRIVATE);
boolean firstLaunch = preferences.getBoolean("firstlaunch", true);
System.out.println("FIRST LAUNCH? " + firstLaunch);
if(firstLaunch == true){
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
editor.putString("language", "en");
editor.putInt("theme", R.style.Default);
editor.putBoolean("firstLaunch", false);
editor.commit();
System.out.println("FIRST LAUNCH:" + preferences.getBoolean("firstLaunch", true));
}
When I restart the app, firstLaunch is still true? Why is this?
You have a case issue.
firstlaunch vs firstLaunch
To avoid this kind of problem you should use a static member.
private static final String KEY_PREFS_NAME = "myPrefs";
private static final String KEY_FIRST_LAUNCH = "firstLaunch";
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE);
boolean firstLaunch = preferences.getBoolean(KEY_FIRST_LAUNCH, true);
System.out.println("FIRST LAUNCH? " + firstLaunch);
if(firstLaunch == true){
SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("language", "en");
editor.putInt("theme", R.style.Default);
editor.putBoolean(KEY_FIRST_LAUNCH, false);
editor.commit();
System.out.println("FIRST LAUNCH:" + preferences.getBoolean(KEY_FIRST_LAUNCH, true));
}
Your key value is not spelled properly when you retrieve it so you always get true change and you commit to the wrong key.
Change
boolean firstLaunch = preferences.getBoolean("firstlaunch", true);
to
boolean firstLaunch = preferences.getBoolean("firstLaunch", true);

reading preferences as int throws exception

I'm trying to read the value stored in preferences as Int, its throwing me classcast exception. Here is the code
SharedPreferences prefs = ct.getSharedPreferences("volumepreference", 0);
SharedPreferences.Editor editor = prefs.edit();
int Past_phone_audio_mode = -1;
try
{
Past_phone_audio_mode = prefs.getInt("volumestate", -1);
}
catch(Exception ee)
{
}
May i know whats wrong in my code
To save a preference int value:
final SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Get preference in editor mode
final SharedPreferences.Editor editor = prefs.edit();
// Set the Integer value
editor.putInt("volumestate", 1);
// Finally, save changes
editor.apply();

how to restore and store two String values?

I have two values how can i store and restore it.
public void SetCaseInfo(String PatientType, String Teethsselected) { // All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PatientType, Teethsselected);
editor.commit();
}
public String getCaseInfo() {
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
String value = settings.getString(PatientType, Teethsselected);
return value;
}
is it correct?
In your code, PatientType must not change so you can be able to retrieve Teethsselected
You are not saving the 2 strings
public void SetCaseInfo(String PatientType, String Teethsselected) { // All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("teeth", Teethsselected);
editor.putString("patient", PatientType);
editor.commit();
}
public String getTeethsselected() {
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
String value = settings.getString("teeth", "default");
return value;
}
public String getPatientType() {
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
String value = settings.getString("patient", "default");
return value;
}
You are storing only one value here:
editor.putString(PatientType, Teethsselected);
here PatientType is the key, not the value you want to save.
Likewise, you are restoring only one value here:
String value = settings.getString(PatientType, Teethsselected);
Teethsselected is the default value for the key PatientType. If it's what you intended, than yes, it is correct.

Categories

Resources