Reputation:
How to save values in preferences (and read) with quite compact way without creating several instances - i want be sure that i have only one instance of pref
Upvotes: 0
Views: 107
Reputation: 1095
CommonsWare is right, but as i understood, you want somehow to structure you job with Preferences, i use singleton for this, something like this:
public class Preferences {
private static final String USERNAME = "username";
private static final String LOG_TAG = Preferences.class.getSimpleName();
private static Preferences sInstance;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private Context mContext;
private Preferences(Context context) {
mContext = context;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
mEditor = mSharedPreferences.edit();
}
public static Preferences getInstance(Context context) {
if (sInstance == null) {
sInstance = new Preferences(context);
}
return sInstance;
}
public void setUsername(String username) {
mEditor.putString(USERNAME, username);
commit();
}
public String getUsername() {
return mSharedPreferences.getString(USERNAME, null);
}
public boolean commit() {
return mEditor.commit();
}
}
And where it is necessary write
Preferences.getInstance(this).setUsername("USERNAME");
and read
Preferences.getInstance(this).getUsername();
Upvotes: 1
Reputation: 1006799
A SharedPreferences
object is a natural singleton. Your first call to read in a SharedPreferences
(e.g., PreferenceManager.getDefaultSharedPreferences()
) will create it. Second and subsequent calls within the same process will return that same instance. Hence, so long as you are consistent about where you get your SharedPreferences
from, you will only ever have one instance (at most) in your process.
Upvotes: 2