I am storing userId at the time of registration in SharedPreferencesand. Now I want to access the SharedPreferences stored UserId value. Till now I tried this code:
prefrence = PreferenceManager.getDefaultSharedPreferences(this);
edit3 = prefrence.edit();
edit3.putInt("user_id", userid);
Log.e("Commit", "SharedPreferences");
edit3.commit();
And on the next activity I am using this for access:
prefr = PreferenceManager.getDefaultSharedPreferences(this);
value = prefr.getInt("user_id", "");
How do I do this?
You PUT in an INT and GET a STRING... Maybe that's causing a type cast error.
I see you changed your code, to get an int... the WRONG WAY!
You are doing so:
value = prefr.getInt("user_id", "");
Instead you should do so:
value = prefr.getInt("user_id", 0);
(You can't assign "" to an int.)
The above is valid if user_id is an int. If user_id is a string, then you should do a putString and a getString. Like:
edit3.putString("user_id", userid);
And then
value = prefr.getString("user_id", "");
So you grant the necessary type consistency.
Try changing
prefr.getString("user_id", "");
to
prefr.getInt("user_id", 0);
Related
I save some String data to SharedPreferences but unfortunately i am unable to get the string value from sharedPreferences.
This is my code to save the data to SharedPreferences
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
userPhone = etPhone.getText().toString();
prefs.edit().putString("userPhone", userPhone).apply();
This saves my number perfectly but when i try to retrieve it in the next activity i get this string instead "userPhone"
This is how i retrieve the string value
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
Log.i("number", phoneNumber);
My logs show phoneNumber as a string instead of the value from the user input that i saved to sharedPrefrences.
For storing values into SharedPreferences you are using Editor and method call:
prefs.edit().putString(String key, String value)
And you did it right:
prefs.edit().putString("userPhone", userPhone).apply();
For retrieving data, we are using the same key as we used for storing. In your case, it is "userPhone".
So, you should do it with:
prefs.getString("userPhone", "Some default value");
But, you mixed key with preferences name and you called
prefs.getString(Config.PREF_NAME, "userPhone");
Here is the difference.
You are actually retrieving the value from:
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
But you need to do :
SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = sharedPreferences.getString("userPhone", null);
It should look like this in your second Activity.
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = prefs.getString("userPhone", "defaultValueIfNoPhoneAvailable");
Log.i("number", phoneNumber);
The second parameter of getString is the default value in case it has no mapping for the key.
I use the following helper to save user input to sharedpreference:
protected void storeData(SharedPreferences.Editor editor,
String key, EditText et) {
String content = et.getText().toString();
if ("".equals(content)||" ".equals(content)) {
editor.remove(key);
} else {
editor.putString(key, content);
}
}
then
number1 = (EditText)findViewById(R.id.number1);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
storeData(editor,"number1", number1);
editor.commit();
I wish to ask if how can I retrieve that value as a integer, then use it for some calculation.
I been searching and found this , found that they use editor.putInt(key,content);
But is that possible to extract the value as integer straight from my method?
thank you.
Your storeData() method is setting a string (putString()). Shared prefs store typed values distinctly different. That is, you cannot put "1" as a string then get it our later as an integer.
You need to use put/getInt() consistently. Alternatively you could store it as a string, and again consistently get it as a string and coerce it to an int as you need.
Your really should be using putInt(), but you can also use Integer.parseInt("some string") to convert your String value to an integer.
Use editor.commit() inside the else part
A suggestion:
use editor.apply() instead of editor.commit() as commit handles the job in foreground whereas apply handles that asynchronously.
I know, the question has been asked long time agao. I came up with similar situation. So, the might help someone in the future.
//for integer values
port = (EditText) findViewById(R.id.devicePort);
int devicePort = Integer.parseInt(port.getText().toString());
editor.putInt(getString(R.string.devicePort), devicePort);
editor.apply();
This is first activity through which i'm saving data in sharedpreferences...
JSONObject obj = new JSONObject(response);
public static String userid;
userid = obj.getString("userid");
String otp = obj.getString("opt");
SharedPreferences sp=getApplicationContext().getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("userid", userid);
editor.putString("opt", otp.toString());
editor.commit();
and i want the value of userid in second activity...
SharedPreferences sp = getApplicationContext().getSharedPreferences("Sharedprefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");
i want the value of "userid" and "otp" which have been stored in "SharedPrefs" sharedprefs, and i dont want to give any default value for this....
Thanks in Advance :)
If above is your code you should change Sharedprefs in the second Preferences to SharedPrefs.
When you store data in SharedPreferences, make sure that Preference name is spelled correctly. It is case sensitive.
Find the difference between "Sharedprefs" and "SharedPrefs".
Try this way.
SharedPreferences sp = getApplicationContext().getSharedPreferences("SharedPrefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");
In my app, the user can add a name and an age for multiple people. Most likely it will only be around 2 or 3. I want to store these in shared preferences. I set a counter to keep track of how many people have been stored as well as to manage which key goes with which value. I took the edittext input and put it in a string and then put it into the shared preferences like so, adding on the counter so I know that is the first person and would access the person with "name1".
//this is in the class
public int count = 1;
//this is in the main
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
Unless I am mistaken, that should put the string "name" into "Name1".
Then I go and try to access it in another activity with...
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name"+count,"");
String age = sharedPreferences.getString("Age"+count,"");
Then i would update the counter before the next person would be added to change the key to "Name2" "Age2", and so on.
Whenever I try to set the strings to a textview, they show up blank. Which means its not the same String to access the key. The putString has to get the "Name1", because even when I try to access the getString("Name",""), it's still blank. Is there something I'm doing wrong or missing. Or there is a better way of doing this? Thanks.
SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
myEditor.apply();//returns nothing,don't forgot to commit changes
also you can use
myEditor.commit() //returns true if the save works, false otherwise.
Is there something I'm doing wrong or missing. Or there is a better
way of doing this?
If SharedPreferences key names are dynamic then you should use SharedPreferences.getAll() which return all keys available in selected preference:
Map<String, ?> allKeys = sharedPreferences.getAll();
Now iterate through allKeys to check key names and get values from Map.Entry related to key like:
for (Map.Entry<String, ?> entry : allKeys.entrySet()) {
Log.v("TAG","Key Name :" entry.getKey());
Log.v("TAG","Key Value :" entry.getValue());
}
You have to call apply() on the shared preference editor after making changes.
...
myEditor.apply();
Shared preferences however, are not meant to store content related data. Consider using more appropriate solutions like a database.
Currently I want to store two different data types as SharedPreference in my android app. Is it possible to store them with the same key-value?
e.g:
int id = 123;
myBoolean = false;
myString = "hello";
SharedPreferences.Editor edit = this.getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
edit.putString(String.valueOf(id), myString);
edit.putBoolean(String.valueOf(id), myBoolean);
because currently, when I try to get the string value I get a ClassCast exception here:
SharedPreferences settings = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String myString = settings.getString(String.valueOf(123), "def");
I get this exception:
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
It is not possible, Shared Preferences is a key value pair (the key is unique). What your code does is replace the previous saved value. So, when you try to get the value you receive a boolean.