reading preferences as int throws exception - android

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

Related

Making a variable value constant in android studio

I'm very new to coding in android, so I barely know any of the syntaxes. I am defining a variable in MainActivity.java and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
Then retrive it with
int number = sharedPref.getInt("key for value";
Sometimes you need to specify a default value like:
SharedPref.getBoolean("is first lunch",true);
Good luck
Use SharedPreference for saving value use this code
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
here are two method
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
Store in Preference if value is 0 else get stored value
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
Retrieve from Preference
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
Just copy and paste above code

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

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

How to save and fetch integer value in Shared Preference in 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

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