How do I use sharedPreferences in Android? - android

I have an Android app which in one of the activities the user check one of the radio buttons. I want to save the user's choice and use its value in another activity.

To store
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.edit().putBoolean("KEY", your_boolean).commit();
To retrieve
Boolean your_boolean = prefs.getBoolean("KEY", false);

You can use shared preference for saving the values.
For Saving value into SharedPreferences use below code
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(
"SHARED_PREF", MODE_PRIVATE).edit();
editor.putString("radio_value", value);
editor.commit();
For Retriving value from SharedPreferences use below code
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"SHARED_PREF", MODE_PRIVATE);
String storedValue = prefs.getString("radio_value","");

Related

value is not getting in sharedpreferences, always default value is coming

I am storing one value in sharedpreferences using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
Editor e = sp.edit();
e.putString("a","unni");
e.commit();
this is in AddBluetooth Activity
Now I am retrieving that value from another activity called Dashboard Activity, which is using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
String aa =sp.getString("a","me");
but its's only returning the default value, how can I fix this issue
IF you're defining your preferences in a preferences.xml you need to access it using SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
// declare this class variable in class from where u will put the string u wanna store in shared pref
//class variables
SharedPreferences pref;
SharedPreferences.Editor editor;
-------------------
//in oncrete method
// declare this in oncreate method
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
// the varibale u wanna put use the below statements
// for string use putString
// for boolean as u need use putBoolean
// have a look at the various option it offers..
editor.putString("selected", "nil");
editor.commit();
// here is the statement use this statement in class where u wanna retireve ur strings
// use getBoolean for Boolean variables
pref.getString("selected", "nil")
// here in sceond parameter in above statement is : if the value u r requesting for that is specified in first parameter is not present then it will return the //value which is your second parameter..
Pull Ur Shared-Pref :
Go to Data-->Data-->Ur package-->Pull The SharedPref file [DDMS]
Actually for me the above code snippet is not working in API 19, but for lower versions its working. So I used,
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=saved_values.edit();
editor.putString("newCEAAddress", address);
editor.commit();
for getting value
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DEVICE_ADDRESS=saved_values.getString("newCEAAddress", "nil");

Cannot get SharedPreferences value from one activity to another in Android

I am using shared preferences for saving data and accessing it from another activity. I have used suggested methods but they don't seem to work.
Code:
private static String Module_Pref="ModulePreference";
Activity A:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Activity B:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tempValue= sharedPreferences.getString(Module_Pref, "empty");
Activity C:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Here if we run first time then pass through A, set nosave, then if we go to activity C then save the data.
What is wrong with this code.I am getting a null. I looked at file explorer also where pref file isn't saved.
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
`
Your should use for entering data like this:
editor.putString(Module_Pref, "value that you want to store");
editor.commit();
Now For getting that String you can use this after storing the value:
sharedPreferences.getString(Module_Pref, "empty");
sharedPreferences.getString(Module_Pref, "empty");
means you want to retrieve the "value" for the key- Module_Pref, if there is none, by default it will return -> "empty" .
So either,
editor.putString(Module_Pref, value);
Or
sharedPreferences.getString(key, "empty");
where "key" is same as the key in:
editor.putString(key, value);
Activity A:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key,value );
editor.commit();
Activity B:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tempValue= sharedPreferences.getString(key, "emptyValue");
SharedPreferences sp = getSharedPreferences("main",0);
SharedPreferences.Editor ed = sp.edit();
ed.putString("personEmail",personEmail);
ed.putString("personName",personName);
ed.commit();
this is used for saving values in shared pref & for accessing it use ->
SharedPreferences sp = getSharedPreferences("main",0);
sp.getString("personEmail",null);
sp.getString("personName",null);

Shared Preferences in not being cleared,

I'm unable to delete SharedPreferences from the app on click event.
Here is how I'm storing the value into UserInfoActivity SharedPreferences:
SharedPreferences notificationCountSP = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor notificationEditor = perkBalance.edit();
notificationEditor.putString("notificationCount",notificationCountValue);
notificationEditor.commit();
And here is how I'm trying to clear all data in SharedPreferences from MainActivity:
SharedPreferences clearNotificationSP = getSharedPreferences(
"notificationCountSP", 0);
SharedPreferences.Editor editor = clearNotificationSP.edit();
editor.remove("notificationCount");
editor.clear();
editor.commit();
Please tell what am I doing wrong with this.
Any kind of help will be appreciated.
SharedPreferences notificationCountSP = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor notificationEditor = notificationCountSP.edit();
notificationEditor.putString("notificationCount", notificationCountValue);
notificationEditor.commit();
notificationEditor.remove("notificationCount");
notificationEditor.commit();
or
SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor editor = clearNotificationSP.edit();
editor.putString("notificationCount", notificationCountValue);
editor.commit();
editor.remove("notificationCount");
editor.commit();
First solution uses the default application preferences file, and the second a custom notification_prefs file.
You are using PreferenceManager.getDefaultSharedPreferences to store but retrieving from getSharedPreferences("notificationCountSP"). They are different files unless you set the default one to "notificationCountSP".
You can do it like below
SharedPreferences userPref = getSharedPreferences(
MyActivity.SHARED_PREFERENCES_FILENAME,MODE_PRIVATE);

How To Use SharedPreference value stored in one activity to another activity

My Code is:
SharedPreferences myPrefs = this.getSharedPreferences("MYPREF'USERID",
Context.MODE_PRIVATE);
int uid = myPrefs.getInt("USERID", 0);
I want to use USERID in another two activities for fetching records
Please help me how to do
Thank You
You can set values in preference as follows
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = pref.edit();
editor.putInt ("USERID", 0);
editor.commit();
and you can retrieve the data form preference as
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = pref.edit();
final int userId= pref.getInt("USERID", -1);
You can get SharedPreferences all around your application by using:
SharedPreferences sharedPreferences = Context.getApplicationContext().getSharedPreferences("pref", Context.MODE_PRIVATE);
You also want to put your values in this global sharedPreference.

Storing data in SharedPreferences accessible to all activities

I want to store and retrieve data that is accessible to all activities in my app using SharedPreferences. Is that possible? Up until now I have been doing it such that the data is stored for a particular activity.
Yes. SharePreferences do exactly this.
In every activity you can this:
SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(name, value);
editor.commit();
And then retrieve values in other activty doing this:
mPrefs.getString(name, "");
This is the documentation:
http://developer.android.com/reference/android/content/SharedPreferences.html
And this is a good example to start with:
http://myandroidsolutions.blogspot.it/2012/03/android-preferenceactivity.html
Yes, that's the whole purpose of it.
Here's how you should write to it, via Editor
final SharedPreferences shp = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor ed = shp.edit();
ed.putString("var1", "var1");
ed.putString("var2", "var2");
And to load it:
shp.getString("var1", "defvalue");
I have a better version. As sometimes when you try to do getSharedPreferences you might get an error as it could not be found.
This is how I store values in my Android projects.
Add
SharedPreferences sharedPreferences=this.getSharedPreferences("packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("username", "specify name here").apply();
Package Name can be directly copied from top of the activity ex: com.example.name.projectname
Retrieve
String username = sharedPreferences.getString("username","");
If you want to access values in all of your activities I think the better way is storing in a custom Application class and later in activities you can:
((CustomApplication)getApplication()).getStoredValue()
Shared preferences are stored in files and this file access is slower.
Is my example for create function for set and get an object data called "USER"
For set sharePreference data
public void saveUser(User usuario) {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", usuario.getNombre());
editor.putString("username", usuario.getUsername());
editor.putString("pass", usuario.getContrasena());
editor.putString("roll",usuario.getRol());
editor.commit();
}
For get sharePreference data
public Usuario getUser() {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
User usuario = new User();
usuario.setNombre(sharedPref.getString("name", "null"));
usuario.setUsername(sharedPref.getString("username", "null"));
usuario.setContrasena(sharedPref.getString("pass", "null"));
usuario.setRol(sharedPref.getString("roll", "null"));
return usuario;
}
Important: set name to sharePreference in this case "A"

Categories

Resources