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.
How to pass data from one activity to another in Android using shared preferences? Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device. To get a handle to a preference file, and to read, write, and manage preference data, use the SharedPreferences class. The Android framework manages the shared preferences file itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With