作为 Android 世界的新人,每天都在快乐地前进;)我想分享一些关于常见用法的例子。
这里是关于将 SharedPreferences 与通用 LocalStore 类一起使用的示例。
创建一个供您的主要活动或任何子活动使用的公共类。
public class LocalStore {
private static final String TAG = "LocalStore";
private static final String PREF_FILE_NAME = "userprefs";
public static void clear(Context context) {
clear(context, "unknown");
}
public static void clear(Context context, String caller) {
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Log.d(TAG, "caller:"+caller + "|clear LocalStore");
}
public static boolean setCustomBooleanData(String key, boolean value, Context context) {
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.putBoolean(key, value);
return editor.commit();
}
public static boolean getCustomBooleanData(String key, Context context) {
SharedPreferences savedSession =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return (savedSession.getBoolean(key, false));
}
public static boolean setCustomStringData(String key, String value, Context context) {
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.putString(key, value);
return editor.commit();
}
public static String getCustomStringData(String key, Context context) {
SharedPreferences savedSession =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return (savedSession.getString(key, null));
}
public static boolean isCustomStringExistInLocal(String customKey, Context context) {
SharedPreferences savedSession =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return (savedSession.getString(customKey, null))==null?false:true;
}
public static boolean saveObject(String objKey, Serializable dataObj, Context context) {
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.putString(objKey, ObjectSerializer.serialize(dataObj) );
Log.d(TAG, "savedObject| objKey:"+objKey+"/" + dataObj.toString());
return editor.commit();
}
public static Object getObject(String objKey, Context context) {
SharedPreferences savedSession =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
Object dataObj = ObjectSerializer.deserialize(savedSession.getString(objKey, null));
return dataObj;
}
}
注意:您可以从这里使用 ObjectSerializer
享受!
附加更新:我实现了一个库来使用 MEMDISKCACHE 和 SHAREDPREF 作为 GENERIC_STORE 任何有兴趣的人都可以从
-> https://github.com/wareninja/generic-store-for-android使用它