not getting integer value from SharedPreference - android

I am trying to store user id in SharedPreference in one activity and want to get this integer id in any activity.
To put this value in Shared Preference i use following code.
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("userId", varaible);
prefsEditor.commit();
Then i am trying to get this value, i use following code for this
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", -1);
But it return me -1 not userId. and if i use following line to fetch integer value then it will showing runtime exception.
int userId = myPrefs.getInt("userId", Integer(null));
I don't understand what's wrong in my code. How to get this integer userId in my another activity.
Please give me any reference or hint.
Thanks in advance.

There is nothing wrong with your code and I tested this exact case and it is working perfectly. For sure you can use the default value as -1.
Do you have both activities in the same application?
What I can suggest for debugging is to make sure that your application runs in the sequence you expect and that the value is stored correctly. You can try to retrieve it directly after storing it within the same activity.

Change this:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", -1);
to this
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
int userId = myPrefs.getInt("userId", 0);
it should work that way.

Related

Share preferences not accesible via IntentService

I am saving a value in Preference, but it always give me the default value. When the app is opened, I can get the actual value. But when I am getting the value from the IntentService, it always give me the default value.
Code for saving the value:
prefs = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Code for reading the value:
prefs = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
String value = prefs.getString(key, defaultValue);
But if i change file name then its working for some period but afterward again it start giving default value
Try changing your access mode from Context.MODE_PRIVATE since you are reading it from outside.
Try
prefs = context.getSharedPreferences(NAME, Context.MODE_MULTI_PROCESS);
Retrieving stuff from Shared Preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Context);
String s = sp.getString("key", null); // get "value" from the Shared Preferences

SharedPreferences deleted for no apparent reason?

I am using following code:
SharedPreferences sharedPref = getSharedPreferences(GlobalDefines.SHARED_PREFERENCES, Context.MODE_PRIVATE);
String test = sharedPref.getString(GlobalDefines.GCM_KEY, "");
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.putBoolean(GlobalDefines.USER_IS_LOGGED_IN, false);
editor.remove(GlobalDefines.USER_NAME);
editor.remove(GlobalDefines.USER_PASSWORD);
editor.commit();
test = sharedPref.getString(GlobalDefines.GCM_KEY, "");
The string "test" has a value when I get the value from the shared preferences for the first time; when I remove another value from the preferences and want to get the same value (GCM_KEY) again, it is returned empty.
Why is that?
editor.clear() tells the editor that you want to remove ALL values from your SharedPreferences. Remove this line and you will see the expected behavior.

How to avoid adding duplicate values in shared preferences in android?

In android, i am adding string values using shared preferences, but i want to compare the value which i am going to add to shared preferences with values which are already stored in shared preferences to avoid adding duplicate values, but i am not getting how to do this?
or is there any alternate method to avoid adding duplicate values in shared preferences?
I am adding string values using following code
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, s);
editor.commit();
In android you cannot really have duplicate value in sharedPreference because every time you change or modify a value on sharedPreference it will replace the previous with the current. So since every instance of it has a single unique key, which mean it will always be unique (in my experience every time i messed up with this keys like giving the same name key for both an Int and boolean for example i end up crashing the app or having some kind of exception)
If im wrong i hope someone else will correct me and provide you with a better answer!
I don't know whether I'm understanding your question quite well or not, but Android's SharedPreferenceshas it's own contains to check if a a key already exists or not.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(NAME)) //It already contains NAME key
On the other hand, if your worries are about a single key's value not to be repeated, just read it before storing the new value and compare themselves, no more.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.getString(NAME, "").equals(s)) {
// It does not have the same value, store 's'
sharedpreferences
.edit();
.putString(NAME, s);
.commit();
}
However, in this particular case I wouldn't perform this verification, just overwrite the value and that's it, as it always gonna be the same.
First get String value from SharedPreferences as oldvalue then compare with newvalue which you want to store. If String not match then save newvalue in SharedPreferences.
Try something like this
String str_newvalue = "new string here";
SharedPreferences sharedpref = this.getSharedPreferences(this.getPackageName(), context.MODE_PRIVATE);
String str_oldvalue = sharedpref.getString("key", "");
if (!str_newvalue.equals(str_oldvalue)) {
sharedpref.edit().putString("key", str_newvalue).commit();
}
Do this
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText.matches(your string))
{
// do nothing
}
else
{
//save your data
}
}

SharedPreferences does not work - getString always returns the default value

I have a problem with SharedPreferences in Android.
This is my code:
SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
s.edit().putString("eur", "1.80");
s.edit().commit();
SharedPreferences a = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
String kurs = a.getString("eur","7");
Toast hhh= Toast.makeText(getApplicationContext(),kurs, Toast.LENGTH_LONG);
hhh.show();
I´m setting the String and want to read it out directly after that in the onCreate method. But i always get the specified default value "7".
What was wrong? I already researched for that problem, but i can´t found helpful things.
Thanks for your help :)
Each time you call "s.edit()" a new editor is created. Thus your "commit()" call is on an instance of the editor that has not had your setting applied. Try this:
SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
Editor editor = s.edit();
editor.putString("eur", "1.80");
editor.commit();
Please try my code below. What i think is wrong in your code, that you are using different "Editor" instances here:
"s.edit().putString("eur", "1.80");"
and here
s.edit().commit();
private static String APP_SHARED_PREFS = "MyAppID";
// Write the value
SharedPreferences.Editor prefsEditor = getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).edit();
prefsEditor.putString("KEY", "VALUE");
prefsEditor.commit();
// Get the value
return getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).getString("KEY", "");
SharedPreferences myPrefs = this.getSharedPreferences("kurs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("eur", "1.80");
// commit the edits
editor.commit();
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", context.MODE_WORLD_READABLE);
String kurs = myPrefs.getString("eur", "7");
Toast hhh= Toast.makeText(getApplicationContext(),kurs, Toast.LENGTH_LONG);
hhh.show();
Try This

Issue with shared preference

I am using Android 2.1 sdk and I am trying to save user loggin session in to Shared preferences, the thing is after saving the value to the shared preference I am unable to retrive it. Here I am pasting the code I used to save and fetch value from SharedPrefrence.
public void setValue(String name, String value, String prefName) {
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
sharedPref.edit().putString(name, value);
sharedPref.edit().commit();
}
public String getValue(String name, String prefName) {
String value = null;
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
value = sharedPref.getString(name, value);
return value;
}
Did i miss some thing in this code, I am not retrieving any exceptions while saving and retrieving the value. Thanks for any help.
Every call to edit() returns you a new Editor instance. So you get an instance, make a change and leave it alone. Then you get a second one and commit that without changes, which results in no value changes in the preferences.
Rather chain in the commit():
sharedPref.edit().putString(name, value).commit();
Alternatively break it up into multiple lines with one specific instance:
Editor e = sharedPref.edit();
e.putString(name, value);
e.commit();
private SharedPreferences myPrefs;
myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Mobile_no", getText_no.getText().toString().trim());
prefsEditor.commit();
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
myPrefs.getString("Mobile_no", "");
try this one code work

Categories

Resources