In an application I have been building we rely on SharedPreferences quite a bit, this got me thinking about what is best practice when it comes to accessing SharedPreferences. For instance many people say the appropriate way to access it is via this call:
PreferenceManager.getDefaultSharedPreferences(Context context)
However it seems like this could be dangerous. If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well. It seems to me that the better call to use would be:
Context.getSharedPreferences(String name, int mode)
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class. You could use the fully qualified name of the class to ensure that the file will most likely not be duplicated by someone else.
Also based on this SO question: Should accessing SharedPreferences be done off the UI Thread?, it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
I've wrote a little article that can also be found here. It describes what SharedPreferences is :
Best Practice: SharedPreferences
Android provides many ways of storing application data. One of those ways leads us to the SharedPreferences object which is used to store private primitive data in key-value pairs.
All logic are based only on three simple classes:
SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener
SharedPreferences
SharedPreferences is main of them. It's responsible for getting (parsing) stored data, provides interface for getting Editor object and interfaces for adding and removing OnSharedPreferenceChangeListener
To create SharedPreferences you will need Context object (can be an application Context)
getSharedPreferences method parses Preference file and creates Map object for it
You can create it in few modes provided by Context. You should always use MODE_PRIVATE, as all the other modes are deprecated since API level 17.
// parse Preference file
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
Editor
SharedPreferences.Editor is an Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
Use simple interface to put values in Editor
Save values synchronous with commit() or asynchronous with apply which is faster. In fact of using different threads using commit() is safer. Thats why I prefer to use commit().
Remove single value with remove() or clear all values with clear()
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
// put values in editor
editor.putBoolean("key", value);
editor.put..("key", value);
// remove single value by key
editor.remove("key");
// remove all values
editor.clear();
// commit your putted values to the SharedPreferences object synchronously
// returns true if success
boolean result = editor.commit();
// do the same as commit() but asynchronously (faster but not safely)
// returns nothing
editor.apply();
Performance & Tips
SharedPreferences is a Singleton object so you can easily get as many references as you want, it opens file only when you call getSharedPreferences first time, or create only one reference for it.
// There are 1000 String values in preferences
SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 4 milliseconds
SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
As SharedPreferences is a Singleton object you can change any of It's instances and not be scared that their data will be different
first.edit().putInt("key",15).commit();
int firstValue = first.getInt("key",0)); // firstValue is 15
int secondValue = second.getInt("key",0)); // secondValue is also 15
Remember the larger the Preference object is the longer get, commit, apply, remove and clear operations will be. So it's highly recommended to separate your data in different small objects.
Your Preferences will not be removed after Application update. So there are cases when you need to create some migration scheme. For example you have Application that parse local JSON in start of application, to do this only after first start you decided to save boolean flag wasLocalDataLoaded. After some time you updated that JSON and released new application version. Users will update their applications but they will not load new JSON because they already done it in first application version.
public class MigrationManager {
private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
private final static int PREFERENCES_VERSION = 2;
public static void migrate(Context context) {
SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
checkPreferences(preferences);
}
private static void checkPreferences(SharedPreferences thePreferences) {
final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
if (oldVersion < PREFERENCES_VERSION) {
final SharedPreferences.Editor edit = thePreferences.edit();
edit.clear();
edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
edit.commit();
}
}
}
SharedPreferences are stored in an xml file in the app data folder
// yours preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
// default preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
Android guide.
Sample Code
public class PreferencesManager {
private static final String PREF_NAME = "com.example.app.PREF_NAME";
private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
private static PreferencesManager sInstance;
private final SharedPreferences mPref;
private PreferencesManager(Context context) {
mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static synchronized void initializeInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesManager(context);
}
}
public static synchronized PreferencesManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return sInstance;
}
public void setValue(long value) {
mPref.edit()
.putLong(KEY_VALUE, value)
.commit();
}
public long getValue() {
return mPref.getLong(KEY_VALUE, 0);
}
public void remove(String key) {
mPref.edit()
.remove(key)
.commit();
}
public boolean clear() {
return mPref.edit()
.clear()
.commit();
}
}
If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well.
Libraries should not use that particular SharedPreferences. The default SharedPreferences should only be used by the application.
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class.
You are certainly welcome to do this. I wouldn't, at the application level, as the primary reason for SharedPreferences is to have them be shared among the components in the application. A development team should have no problem managing this namespace, just as they should have no problem managing names of classes, packages, resources, or other project-level stuff. Moreover, the default SharedPreferences are what your PreferenceActivity will use.
However, going back to your libraries point, reusable libraries should use a separate SharedPreferences for their library only. I would not base it on a class name, because then you are one refactoring away from breaking your app. Instead, pick a name that is unique (e.g., based on the library name, such as "com.commonsware.cwac.wakeful.WakefulIntentService") but stable.
it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Ideally, yes. I recently released a SharedPreferencesLoader that helps with this.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
Don't over-rely upon them. They are stored in XML files and are not transactional. A database should be your primary data store, particularly for data you really don't want to lose.
In kotlin, use of SharedPreferences can be simplified in the following way.
class Prefs(context: Context) {
companion object {
private const val PREFS_FILENAME = "app_prefs"
private const val KEY_MY_STRING = "my_string"
private const val KEY_MY_BOOLEAN = "my_boolean"
private const val KEY_MY_ARRAY = "string_array"
}
private val sharedPrefs: SharedPreferences =
context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)
var myString: String
get() = sharedPrefs.getString(KEY_MY_STRING, "") ?: ""
set(value) = sharedPrefs.edit { putString(KEY_MY_STRING, value) }
var myBoolean: Boolean
get() = sharedPrefs.getBoolean(KEY_MY_BOOLEAN, false)
set(value) = sharedPrefs.edit { putBoolean(KEY_MY_BOOLEAN, value) }
var myStringArray: Array<String>
get() = sharedPrefs.getStringSet(KEY_MY_ARRAY, emptySet())?.toTypedArray()
?: emptyArray()
set(value) = sharedPrefs.edit { putStringSet(KEY_MY_ARRAY, value.toSet()) }
Here, sharedPrefs.edit{...} is provided by the android core ktx library and should be implemented by adding dependency implementation "androidx.core:core-ktx:1.0.2" in appliation level build.gradle.
You can get the instance of SharedPreferences by using code:
val prefs = Prefs(context)
Furthermore, you can create the Singleton object of Prefs and use from anywhere within the app.
val prefs: Prefs by lazy {
Prefs(App.instance)
}
where, App extends Application and should be included in AndroidManifest.xml
App.kt
class App:Application() {
companion object {
lateinit var instance: App
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest .....
<application
android:name=".App"
....
Example Usage:
// get stored value
val myString = prefs.myString
// store value
prefs.myString = "My String Value"
// get stored array
val myStringArray = prefs.myStringArray
// store array
prefs.myStringArray = arrayOf("String 1","String 2","String 3")
This is my way
for write
SharedPreferences settings = context.getSharedPreferences("prefs", 0);
SharedPreferences.Editor editore = settings.edit();
editore.putString("key", "some value");
editore.apply();
to read
SharedPreferences settings = getSharedPreferences("prefs", 0);
Strings value = settings.getString("key", "");
Let's assume in a project, with multiple developers working on it, they are defining SharedPreference within an Activity like this:
SharedPreferences sharedPref = context.getSharedPreferences("prefName", 0);
At one point or another two developers can define the SharedPreference with the same name or insert equivalent Key - Value pairs, which will lead to problems in using the keys.
The solution relies on two options, whether to use;
SharedPreferences Singleton that uses String keys.
SharedPreferences Singleton that uses Enum keys.
Personally and According to this Sharepreference Documentation, I prefer to use Enum keys as it enforces stricter control when there are multiple programmers working on a project. A programmer has no choice but to declare a new key in the appropriate enum class and so all the keys are in the same place.
And to avoid boilerplate code writing create the SharedPreference singleton.
This SharedPreferences singleton Class help to centralize and simplify reading and writing of SharedPreferences in your Android app.
The source code for the two provided solutions can be found in GitHub
Related
I have this simple module SharePreferencesModule.java :
#Module(includes = ApplicationModule.class)
public class SharedPreferencesModule {
#Provides
SharedPreferences sharedPreferences(MyApp app) {
return app.getSharedPreferences("...", Context.MODE_PRIVATE);
}
#Provides
#Named("firstname")
static String getFirstname(SharedPreferences preferences) {
return preferences.getString("firstname", "");
}
}
With this component SharedPreferencesComponent.java :
#Component(modules = SharedPreferencesModule.class)
public interface SharedPreferencesComponent {
void inject(MyFragment myClass);
}
And this class, which is using the module :
public MyFragment extends Fragment {
#Inject
#Name("firstname")
String firstname;
#Override
public void onAttach(Context context) {
// Not posting "Injector" code in the snippet because it is irrelevant
Injector.getSharedPreferencesComponent().inject(this);
}
}
When MyFragment is created I successfully inject the firstname, but if edit the shared prefs, I am still referencing the old value of firstname. Which is normal because Dagger is providing the firstname only when MyFragment is attached.
How can I stay up to date with the shared prefs ?
Should I re-inject MyFragment everytime the shared prefs are updated ? Seems messy to me.
Or can I somehow force Dagger to fetch this data for me ?
Should I re-inject MyFragment everytime the shared prefs are updated ?
You should only inject once, in the same way that you don't call the constructor multiple times.
There might be some exceptions where it would indeed be necessary (or preferrable) to inject again, but all of those injections should happen before you start using your objects. Injecting multiple times leads to an inconsistent state where it is unclear which object references which version of your injected objects.
This might work in some cases, but will lead to difficult bugs in others, and either way you will have a hard time to set it up, making sure to update everything. You'd be better off just destroying and recreating the whole fragment everytime something changes.
Injecting an object should be the initial setup that gets done once and after that the class should be ready to use.
If something keeps changing then Dagger is not the best fit to provide it. Your name would possibly be better put in some NameSettings class
class NameSettings {
private SharedPreferences prefs;
#Inject NameSettings(SharedPreferences prefs) {
this.prefs = prefs;
}
String getName() { return /* load from prefs */ }
void setName(String name) { /* save to prefs */ }
}
Instead of direcyly injecting a name you could now inject NameSettings and call get / set to update your name. This way you can always read and write the latest value without the need to deal with SharedPreferences directly.
Now your NameSettings would not change and there would be no need to re-inject it either.
You could even go ahead and return an Observable (e.g. RxJava, or some custom implementation of an observable pattern) where you can then listen for changes and update your UI dynamically whenever it changes.
I would #Provide the SharedPreferences object itself. This minimizes the dependency graph and makes you read/write any preference.
I'm new to the amazing world of java, but my Obj-C experince tells me that this code:
Preferences prefs = Preferences.userRoot();
String tickets = prefs.get("tickets", "???");
Log.d("Prefs", tickets);
prefs.put("tickets", "!!!");
should produce ??? on the first run, and !!! on the second run. But it does not. I see ??? all the time.
What am I missing? Maybe some permissions? Maybe calling some save() method on prefs object?
I've also tried:
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
No luck either.
I think you're probably looking for SharedPreferences... "context" is your Activity or Application
try:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String tickets = prefs.getString("tickets", "???");
Log.d("Prefs", tickets);
prefs.edit().putString("tickets", "!!!").commit();
Seems like you want to use SharedPreferences to store some data. In order to write to preferences try this function:
public void putPref(Context context, String key, String value){
SharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = SharedPrefs.edit();
editor.putString(key, value);
editor.commit();
}
If you want to put the value "???" using key "tickets" use:
putPref(context, "tickets", "???");
You can retrieve that value by using:
SharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
If you want to get value for the key "ticket" use:
SharedPrefs.getString("tickets", "default");
where "default" is the default value if the preference isn't found. Hope this helps.
You can save the values to preference using the below function
public static void saveTickets(String customerId,Context context)
{
SharedPreferences preferences;
preferences = context.getSharedPreferences("sample",Context.MODE_PRIVATE);
preferences.edit().putString("tickets", customerId).commit();
}
Get the values from preference using the below function. The parameter you need to pass is just context
public static String getTickets(Context context)
{
SharedPreferences preferences;
preferences = context.getSharedPreferences("sample",Context.MODE_PRIVATE);
String customerId = preferences.getString("tickets", "");
return customerId;
}
I have a basic understanding of java and android but am still new and am struggling to find the correct way to save a variable and be able to access it/read it from other classes/activities. I have seen singletons but I am confused if it is the right way and how it would look, also do I need to make sure its thread safe?
Is there a better way that I am unaware of?
Basically I have a login that gets a username and some info about that user. How can I save that to a class/singleton and access it later?
EDIT
after some more searching I found this example:
public class Drivers {
private static Array drivers;
public static void setDrivers(Array c){
drivers = c;
}
public static Array getDrivers(){
return drivers;
}
}
and get and set like this:
public class AnyClass {
{
int clicks = ActionClass.getDrivers();
ActionClass.setDrivers(0);
}
Would this work/be correct?
Create a Constant Class like :
public class Constant {
public static String USERNAME = "";
public static String PASSWORD = "";
}
Now, you can set this value in Activity1 like
Constant.USERNAME = "uname";
Constant.PASSWORD= "password";
Now, get this value in Activity2 like:
String u_name = Constant.USERNAME;
String pass = Constant.PASSWORD;
You can access this variables any where in your app.
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
You could use SharedPreferences (kind of a persistence layer). Or you could pass data through Intent.
You can use sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("PASSWORD_KEY", mPassword);
editor.commit();
String s = sharedPreferences.getString("PASSWORD_KEY", ""); // get the saved string
I have two classes, one loggedIn, and a User class. In the loggedIn class I want to show the shared preferences that I made when the user logs in.
loginPrefs = getSharedPreferences("loginpreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor loginEditor = loginPrefs.edit();
loginEditor.putString("userID", userIDCrypt);
loginEditor.commit();
Now i want to make in the user class a getID() method, that I can call the method from every class with User.getID();. How can I do this?
I need the userID in multiple classes, so I want one activity (called getID e.g.) that gives me the user ID.
try this in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("name", username);
edit.putString("pwd", password);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("name", "default value"));
sp.getString("pwd", "default value"));
do like this make one class for your sharedpreference
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
prefsCommit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
now after making this class when u want to use this use like this
make object og this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
and now we set sharedpreference then use this like
session.setusename("USERNAME");
now when ever u want to get username then same work for session object and call this
session.getusename();
best of luck :) same for password
Sorry if there is any syntax or compilation issues, just typing out of my head, and might make some mistakes. So in essence this is an approach that you can use to expose your prefs from one simple class and access it from any where.
public class MySharedPrefs {
public SharedPreferences sp;
public MySharedPrefs()
{
this.sp = c.getSharedPreferences("prefs", Context.MODE_PRIVATE);
}
public static String getStringFieldValue(Context c, String fieldName)
{
MySharedPrefs p = new MySharedPrefs(c);
return p.sp.getString(fieldName, "default value");
}
public static void setStringValue(Context c, String fieldName, String value)
{
MySharedPrefs p = new MySharedPrefs(c);
SharedPreferences.Editor edit;
edit = p.sp.edit();
edit.putString(fieldName, value);
edit.commit();
}
}
Then use it like this in your activity:
MySharedPrefs.getStringFieldValue(this, "name");
You can the also expand on this class and add additional helper methods such as a getUserName or etc.
UPDATE:
When calling this from another static class, that class needs to have a reference to your applications context, you then need to provide that context to this function instead of using this.
MySharedPrefs.getStringFieldValue(context, "name"); //if your other static class has a property called context that contains your applications context
so I've been working on a project that receives data from server, for example sessionKey. I created getter and setter method like this :
public class sEngine
{
private static String sessionKey;
public static String getSessionKey() {
return sessionKey;
}
public static void setSessionKey(
String sessionKey) {
sEngine.sessionKey = sessionKey;
}
}
Then I have activity A. In this activity A, I insert a value into the setter method.
public class A extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
sEngine.setSessionKey("Hello world")
}
}
I also have activity B. In this activity B, I call the getter method
public class B extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
String sessionKey = sEngine.getSessionKey();
}
}
It occurs to me, that Android sometimes wipes all the data in order to free some memory, for example when I let the program idle for too long, or I used Advanced Task Killer. The problem is if those happen, I will get null in activity B when I call the getter method although I've set the value in activity A. Is there any way for me to maintain the value stored via the setter method (other than using SharedPreference) so the value will still be there although Android wipes the memories/data?
Is there any way for me to maintain the value stored via the setter
method (other than using SharedPreference) so the value will still be
there although Android wipes the memories/data?
Not sure why you wouldn't want to use SharedPreferences, despite it being the perfect candidate in your requirement. When somethings as simple as this can store it:
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(SOME_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPrefs.edit();
editor.putString("session_key", sessionKey );
This will ensure your sessionkey always remains stored for easy retrieval. Unless the user clears your app data that is.
Your only alternatives as opposed to SharedPreferences are saving the sessionkey to a Database which in my opinion, considering the task it will perform, is absolutely unnecessary.
You could also consider writing the sessionkey to a text file and then read it to retrive the data.
Both the alternatives to SharedPreferences are truly unfit for the purpose you need it for. And I would really urge you to re-consider using SharedPreferences .
Try this, Declare you non activity class in A Activity. and then set your session value.
sEngine mengine = new sEngine();
mengine.setSessionKey("Hello world");
And also get session value in B activity.
sEngine mengine = new sEngine();
String str = mengine.getSessionKey();
change
sEngine.sessionKey = sessionKey;
in your code to
this.sessionKey = sessionKey;
or simply
sessionKey = sessionKey;
using sEngine. makes one believe that your class is static.Which it isnt!
or if you want to use this sEngine. everywhere in your code you need to declare this class as static.In that case you just need to make the class declaration to static:
public static class sEngine {