问题
i am trying to write a singleton class to oversee all operations involving shared preferences.
I have 3 preference files, general, settings, and temp
I want to be able to use this class to write a preference of a given type, for example:
stg_full_screen: true // as boolean
This is what i have done so far:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPrefManager extends Activity {
// Globals
private int GENERAL = 1000;
private int SETTINGS = 2000;
private int TEMP_STORE = 3000;
private String PREF_GENERAL = "com.example.general";
private String PREF_SETTINGS = "com.example.settings";
private String PREF_TEMP_STORE = "com.example.temp_store";
private SharedPreferences general;
private SharedPreferences settings;
private SharedPreferences tempStore;
private SharedPreferences.Editor general_editor;
private SharedPreferences.Editor settings_editor;
private SharedPreferences.Editor temp_store_editor;
// Instantiate singleton object
private static SharedPrefManager ourInstance = new SharedPrefManager();
public static SharedPrefManager getInstance() { return ourInstance; }
private SharedPrefManager() {
// Get handle on all preference files
general = getSharedPreferences(PREF_GENERAL, Context.MODE_PRIVATE);
settings = getSharedPreferences(PREF_SETTINGS, Context.MODE_PRIVATE);
tempStore = getSharedPreferences(PREF_TEMP_STORE, Context.MODE_PRIVATE);
// provision editors for all preference files
general_editor = general.edit();
settings_editor = settings.edit();
temp_store_editor = tempStore.edit();
}
private String read_prefs (String pref_name) {
// this method reads a preference and returns it
// ideally, i would want to be able to return appropriate types by request
// e.g boolean, string
return null;
}
private void write_prefs (String pref_name, String pref_val) {
// this method would take a preference and write the appropriate type to prefs
}
// this method determines where to put a preference by checking the name of the key
// this works because i use the following naming conventions
// stg_name for settings, tmp_name for all that goes into tempStore
private String resolve_pref_category (String path) {
if (path.startsWith("stn")) return PREF_SETTINGS;
else if (path.startsWith("tmp")) return PREF_TEMP_STORE;
else return PREF_GENERAL;
}
}
My question is:
- Is this a wise thing to do?
- How can i efficiently determine the type of a preference?
Thanks
回答1:
Usually, I use something like this:
No static Context
reference, static getter/setter for each property, when required you can add memory cached value for some property to get it faster from memory instead of reading from SharedPreferences. Clear api.
public class SharedPreferencesManager {
private static final String APP_SETTINGS = "APP_SETTINGS";
// properties
private static final String SOME_STRING_VALUE = "SOME_STRING_VALUE";
// other properties...
private SharedPreferencesManager() {}
private static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(APP_SETTINGS, Context.MODE_PRIVATE);
}
public static String getSomeStringValue(Context context) {
return getSharedPreferences(context).getString(SOME_STRING_VALUE , null);
}
public static void setSomeStringValue(Context context, String newValue) {
final SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString(SOME_STRING_VALUE , newValue);
editor.commit();
}
// other getters/setters
}
回答2:
Proper Singleton Shared Preferences Class. it may help others in the future.
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
Simply call SharedPref.init() on MainActivity once
SharedPref.init(getApplicationContext());
Write data
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, "25");//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
Read Data
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
String age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
String isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
Output
Name : "XXXX";
Age : "25";
IsSelect : "true";
回答3:
Kotlin solution:
object PrefsHelper {
private lateinit var prefs: SharedPreferences
private const val PREFS_NAME = "params"
const val ID_USER = "id_user"
const val TOKEN = "token"
fun init(context: Context) {
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
}
fun read(key: String, value: String): String? {
return prefs.getString(key, value)
}
fun read(key: String, value: Long): Long? {
return prefs.getLong(key, value)
}
fun write(key: String, value: String) {
val prefsEditor: SharedPreferences.Editor = prefs.edit()
with(prefsEditor) {
putString(key, value)
commit()
}
}
fun write(key: String, value: Long) {
val prefsEditor: SharedPreferences.Editor = prefs.edit()
with(prefsEditor) {
putLong(key, value)
commit()
}
}
}
Call init()
function on first app’s run.
回答4:
SharedPreferences Singleton with ApplicationContext
public class SharedPrefsSingleton {
private SharedPreferences sharedPref;
private Context appContext;
private static SharedPrefsSingleton instance;
public static synchronized SharedPrefsSingleton getInstance(Context applicationContext){
if(instance == null)
instance = new SharedPrefsSingleton(applicationContext);
return instance;
}
private SharedPrefsSingleton(Context applicationContext) {
appContext = applicationContext;
sharedPref = appContext.getSharedPreferences(
appContext.getString(R.string.key_pref), Context.MODE_PRIVATE );
}
public void writeData(float value) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat(appContext.getString(R.string.key_data), value);
editor.apply();
}
public float readData() {
return sharedPref.getFloat(appContext.getString(R.string.key_data), 0);
}
}
回答5:
import android.content.Context; import android.content.SharedPreferences;
import com.example.day.weeklypapers.model.LoginModel; import com.google.gson.Gson;
public class WeeklyPreference {
private static WeeklyPreference mInstance = null;
private static SharedPreferences mPreferences;
private static SharedPreferences.Editor mEditor;
private Context context;
private static String SharedPreferenceKey = "Weekly" ;
private WeeklyPreference() {
}
public static WeeklyPreference getInstance(Context context) {
if (mInstance == null) {
mInstance = new WeeklyPreference();
}
if (mPreferences == null) {
mPreferences = context.getApplicationContext().getSharedPreferences(SharedPreferenceKey, Context.MODE_PRIVATE);
mEditor = mPreferences.edit();
mEditor.commit();
}
return mInstance;
}
public void saveInPreference(String key, String value) {
mEditor.putString(key, value);
mEditor.commit();
}
public String getFromPreference(String key) {
return mPreferences.getString(key, "");
}
public LoginModel getUserDetails() {
String userJson = mPreferences.getString(PrefrenceConstants.KEY_USER_JSON_DETAILS, "");
LoginModel user = null;
if (userJson != null && !userJson.equals("")) {
user = new Gson().fromJson(userJson, LoginModel.class);
}
return user;
}
public void saveUserDetails(LoginModel user) {
mEditor.putString(PrefrenceConstants.KEY_USER_JSON_DETAILS, new Gson().toJson(user));
mEditor.commit();
}
public boolean isAutoLogin() {
String userJson = mPreferences.getString(PrefrenceConstants.KEY_USER_JSON_DETAILS, "");
LoginModel user = null;
if (userJson != null && !userJson.equals("")) {
user = new Gson().fromJson(userJson, LoginModel.class);
return user != null;
} else {
return false;
}
}
}
You can pass direct your pojo class or Model class in this singleton class reduce your effort
Take Care .. Enjoy..
来源:https://stackoverflow.com/questions/19612993/writing-singleton-class-to-manage-android-sharedpreferences