Storing data in SharedPreferences accessible to all activities - android

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"

Related

how to pass data to more number of activities

I would like to pass data from one activity to another.If it is two or three activities we can send data via intent.suppose more number of activities are present (approximately 20).how can i pass data from first activity to last activity?
i want to go Activity A-->B-->C-->D-->......Y-->Z
if we send data via intent(put Extra) that is worst method.
is there any other way to send data?
thanks in advance
I would use SharedPreferences for this.
This will be easier because, we can change it anywhere in any activity and access them as needed. And we don't need to pass on each and every activity transition.
Simple example:
To set value in shared preference
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Nabin");
editor.putInt("idName", 12);
editor.commit();
And retrieve as
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
You can refer here more about it.
If you need some data to multiple activities, Just save data into SharedPreference and you will be able to access to all activities.
Here is full tutorial.
Save Data
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor= sharedPref.edit();
//put your value
editor.putString("name", strName);
editor.putString("pwd", strPass);
editor.commit(); //commits your edits
Retrieve Data
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
String password = sharedPref.getString("pwd", "");
If it's not a must case to use activities, you can change activities to fragments, attach them to same activity, cache your data in activity and get it from fragments.

How do I use sharedPreferences in 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","");

Can't get SharedPreferences with activity

Sorry for my bad English.
On my application, I save token (it's a web app) in shared preferences. In first activity I do this:
(token = 123)
SharedPreferences sp = getPreferences(MODE_PRIVATE);
Editor ed = sp.edit();
ed.putString("token", Main.getToken());
ed.commit();
Log.d("Recieved token: ", sp.getString("token", "null")); // Recieved token: 123
As you see, shared prefs are saved.
I have another activity, which may be called from browser to share link.
Code:
sp = getPreferences(MODE_PRIVATE);
Log.d("Token recieved: ", sp.getString("token", "null")); // null
But on another activity shared prefs return null.
What can I do?
To explain the reason why getPreferences() didn't work for you:
When you call getPreferences() without specifying a Shared Preferences name, it returns a Shared Preference using the calling Activity's class name as the Shared Preference name. That's why you are getting null in your other activity - it's actually a different Shared Preference set that you are referring to.
Use getSharedPreferences instead, using whatever preferences name you like:
getSharedPreferences("my_prefs", Activity.MODE_PRIVATE);
That will then be available throughout your application. However using getPreferences() is suitable where you don't need to refer to the data stored outside of a particular Activity.
use like following,,
SharedPreferences mAppSettings = getSharedPreferences("SharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = mAppSettings.edit();
prefEditor.putString(""token, "");
prefEditor.commit();
for retrieving,,,
final SharedPreferences mAppSettings1 = getSharedPreferences(
"SharedPref", MODE_PRIVATE);
String token= mAppSettings1.getString("token", "");

SharedPreferences

I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.

Data cache in Shared Preference

I have 2 processes in my application. From one process i save data in to SharedPreferences.
From second process - retrieve. When i retrieve data, i receive SharedPreferences with old data(i check xml file and see, that currently data in file and data that was received are different). It looks like this data was cached. I changed saving methods (commit/apply) but no result.
PS: just for example http://pastebin.com/Zx2ffvSg
//saving
{ ...
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, "Sai");
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
... }
//retrieving
// when i call getData() I put "this" as argument.
public void getData(Context context){
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
...}
The solution is add to neccesary flags Context.MODE_MULTI_PROCESS flag when open shared preference (Available in API Level 11 and up)

Categories

Resources