我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
有两个文件解决了共享首选项的所有问题
1)AppPersistence.java
public class AppPersistence {
public enum keys {
USER_NAME, USER_ID, USER_NUMBER, USER_EMAIL, USER_ADDRESS, CITY, USER_IMAGE,
DOB, MRG_Anniversary, COMPANY, USER_TYPE, support_phone
}
private static AppPersistence mAppPersistance;
private SharedPreferences sharedPreferences;
public static AppPersistence start(Context context) {
if (mAppPersistance == null) {
mAppPersistance = new AppPersistence(context);
}
return mAppPersistance;
}
private AppPersistence(Context context) {
sharedPreferences = context.getSharedPreferences(context.getString(R.string.prefrence_file_name),
Context.MODE_PRIVATE);
}
public Object get(Enum key) {
Map<String, ?> all = sharedPreferences.getAll();
return all.get(key.toString());
}
void save(Enum key, Object val) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (val instanceof Integer) {
editor.putInt(key.toString(), (Integer) val);
} else if (val instanceof String) {
editor.putString(key.toString(), String.valueOf(val));
} else if (val instanceof Float) {
editor.putFloat(key.toString(), (Float) val);
} else if (val instanceof Long) {
editor.putLong(key.toString(), (Long) val);
} else if (val instanceof Boolean) {
editor.putBoolean(key.toString(), (Boolean) val);
}
editor.apply();
}
void remove(Enum key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key.toString());
editor.apply();
}
public void removeAll() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
2)AppPreference.java
public static void setPreference(Context context, Enum Name, String Value) {
AppPersistence.start(context).save(Name, Value);
}
public static String getPreference(Context context, Enum Name) {
return (String) AppPersistence.start(context).get(Name);
}
public static void removePreference(Context context, Enum Name) {
AppPersistence.start(context).remove(Name);
}
}
现在你可以保存,删除或者获取,
保存
AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);
删除
AppPreference.removePreference(context, AppPersistence.keys.USER_ID);
-get
AppPreference.getPreference(context, AppPersistence.keys.USER_ID);
其他回答
有两个文件解决了共享首选项的所有问题
1)AppPersistence.java
public class AppPersistence {
public enum keys {
USER_NAME, USER_ID, USER_NUMBER, USER_EMAIL, USER_ADDRESS, CITY, USER_IMAGE,
DOB, MRG_Anniversary, COMPANY, USER_TYPE, support_phone
}
private static AppPersistence mAppPersistance;
private SharedPreferences sharedPreferences;
public static AppPersistence start(Context context) {
if (mAppPersistance == null) {
mAppPersistance = new AppPersistence(context);
}
return mAppPersistance;
}
private AppPersistence(Context context) {
sharedPreferences = context.getSharedPreferences(context.getString(R.string.prefrence_file_name),
Context.MODE_PRIVATE);
}
public Object get(Enum key) {
Map<String, ?> all = sharedPreferences.getAll();
return all.get(key.toString());
}
void save(Enum key, Object val) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (val instanceof Integer) {
editor.putInt(key.toString(), (Integer) val);
} else if (val instanceof String) {
editor.putString(key.toString(), String.valueOf(val));
} else if (val instanceof Float) {
editor.putFloat(key.toString(), (Float) val);
} else if (val instanceof Long) {
editor.putLong(key.toString(), (Long) val);
} else if (val instanceof Boolean) {
editor.putBoolean(key.toString(), (Boolean) val);
}
editor.apply();
}
void remove(Enum key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key.toString());
editor.apply();
}
public void removeAll() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
2)AppPreference.java
public static void setPreference(Context context, Enum Name, String Value) {
AppPersistence.start(context).save(Name, Value);
}
public static String getPreference(Context context, Enum Name) {
return (String) AppPersistence.start(context).get(Name);
}
public static void removePreference(Context context, Enum Name) {
AppPersistence.start(context).remove(Name);
}
}
现在你可以保存,删除或者获取,
保存
AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);
删除
AppPreference.removePreference(context, AppPersistence.keys.USER_ID);
-get
AppPreference.getPreference(context, AppPersistence.keys.USER_ID);
我知道这个帖子有点旧了。 但我还是要把这个贴出来,希望它能帮助到一些人。 通过将对象序列化为String,可以将任何Object的字段存储为共享首选项。 这里我使用GSON存储共享首选项的任何对象。
保存对象到首选项:
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
从首选项检索对象:
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
注意:
记得在gradle的dependencies中添加compile 'com.google.code.gson:gson:2.6.2'。
例子:
//assume SampleClass exists
SampleClass mObject = new SampleObject();
//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
更新:
正如@Sharp_Edge在评论中指出的那样,上述解决方案不适用于List。
稍微修改一下getSavedObjectFromPreference()的签名——从Class<GenericClass> classType到Type classType将使这个解决方案一般化。修改后的函数签名
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
用于调用,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
编码快乐!
我的utils类保存列表到SharedPreferences
public class SharedPrefApi {
private SharedPreferences sharedPreferences;
private Gson gson;
public SharedPrefApi(Context context, Gson gson) {
this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.gson = gson;
}
...
public <T> void putObject(String key, T value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, gson.toJson(value));
editor.apply();
}
public <T> T getObject(String key, Class<T> clazz) {
return gson.fromJson(getString(key, null), clazz);
}
}
使用
// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
. 我的utils的完整代码//检查使用实例的活动代码
如果你的对象很复杂,我建议序列化/XML/JSON,并将这些内容保存到SD卡。你可以在这里找到关于如何保存到外部存储的其他信息: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
另一种不使用Json格式保存和恢复android sharedpreferences对象的方法
private static ExampleObject getObject(Context c,String db_name){
SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
ExampleObject o = new ExampleObject();
Field[] fields = o.getClass().getFields();
try {
for (Field field : fields) {
Class<?> type = field.getType();
try {
final String name = field.getName();
if (type == Character.TYPE || type.equals(String.class)) {
field.set(o,sharedPreferences.getString(name, ""));
} else if (type.equals(int.class) || type.equals(Short.class))
field.setInt(o,sharedPreferences.getInt(name, 0));
else if (type.equals(double.class))
field.setDouble(o,sharedPreferences.getFloat(name, 0));
else if (type.equals(float.class))
field.setFloat(o,sharedPreferences.getFloat(name, 0));
else if (type.equals(long.class))
field.setLong(o,sharedPreferences.getLong(name, 0));
else if (type.equals(Boolean.class))
field.setBoolean(o,sharedPreferences.getBoolean(name, false));
else if (type.equals(UUID.class))
field.set(
o,
UUID.fromString(
sharedPreferences.getString(
name,
UUID.nameUUIDFromBytes("".getBytes()).toString()
)
)
);
} catch (IllegalAccessException e) {
Log.e(StaticConfig.app_name, "IllegalAccessException", e);
} catch (IllegalArgumentException e) {
Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
}
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return o;
}
private static void setObject(Context context, Object o, String db_name) {
Field[] fields = o.getClass().getFields();
SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for (Field field : fields) {
Class<?> type = field.getType();
try {
final String name = field.getName();
if (type == Character.TYPE || type.equals(String.class)) {
Object value = field.get(o);
if (value != null)
editor.putString(name, value.toString());
} else if (type.equals(int.class) || type.equals(Short.class))
editor.putInt(name, field.getInt(o));
else if (type.equals(double.class))
editor.putFloat(name, (float) field.getDouble(o));
else if (type.equals(float.class))
editor.putFloat(name, field.getFloat(o));
else if (type.equals(long.class))
editor.putLong(name, field.getLong(o));
else if (type.equals(Boolean.class))
editor.putBoolean(name, field.getBoolean(o));
else if (type.equals(UUID.class))
editor.putString(name, field.get(o).toString());
} catch (IllegalAccessException e) {
Log.e(StaticConfig.app_name, "IllegalAccessException", e);
} catch (IllegalArgumentException e) {
Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
}
}
editor.apply();
}