我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
我知道这个帖子有点旧了。 但我还是要把这个贴出来,希望它能帮助到一些人。 通过将对象序列化为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)
编码快乐!
其他回答
如果你想存储你从响应中得到的整个对象,它可以通过这样做来实现,
首先,在util类中创建一个将JSON转换为字符串的方法,如下所示。
public static <T> T fromJson(String jsonString, Class<T> theClass) {
return new Gson().fromJson(jsonString, theClass);
}
然后在共享偏好类中执行如下操作,
public void storeLoginResponse(yourResponseClass objName) {
String loginJSON = UtilClass.toJson(customer);
if (!TextUtils.isEmpty(customerJSON)) {
editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
editor.commit();
}
}
然后为getPreferences创建一个方法
public Customer getCustomerDetails() {
String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
if (!TextUtils.isEmpty(customerDetail)) {
return GSONConverter.fromJson(customerDetail, Customer.class);
} else {
return new Customer();
}
}
然后只是调用第一个方法时,你得到的响应和 其次,当你需要从分享偏好中获取数据时
String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();
这是所有。
希望对你有所帮助。
快乐的编码();
另一种不使用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();
}
这么多好答案,她是我的2美分
我更喜欢使用内联函数和旧风格的put和get值
object PreferenceHelper {
private const val PREFERENCES_KEY = "MyLocalPreference"
private fun getPreference(context: Context): SharedPreferences {
return context.getSharedPreferences(
PREFERENCES_KEY,
Context.MODE_PRIVATE
)
}
fun setBoolean(appContext: Context, key: String?, value: Boolean?) =
getPreference(appContext).edit().putBoolean(key, value!!).apply()
fun setInteger(appContext: Context, key: String?, value: Int) =
getPreference(appContext).edit().putInt(key, value).apply()
fun setFloat(appContext: Context, key: String?, value: Float) =
getPreference(appContext).edit().putFloat(key, value).apply()
fun setString(appContext: Context, key: String?, value: String?) =
getPreference(appContext).edit().putString(key, value).apply()
// To retrieve values from shared preferences:
fun getBoolean(appContext: Context, key: String?, defaultValue: Boolean?): Boolean =
getPreference(appContext).getBoolean(key, defaultValue!!)
fun getInteger(appContext: Context, key: String?, defaultValue: Int): Int =
getPreference(appContext)
.getInt(key, defaultValue)
fun getString(appContext: Context, key: String?, defaultValue: String?): String? =
getPreference(appContext)
.getString(key, defaultValue)
}
使用
PreferenceHelper.setString(context,"CUSTOMER_NAME", "HITESH")
Toast.makeText(context, "Hello " + PreferenceHelper.getString(context,"CUSTOMER_NAME", "User"), Toast.LENGTH_LONG).show()
如果你的对象很复杂,我建议序列化/XML/JSON,并将这些内容保存到SD卡。你可以在这里找到关于如何保存到外部存储的其他信息: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
在SharedPreferences中存储Model的数组列表
Add this dependency implementation 'com.google.code.gson:gson:2.8.8' Then after you convert your Model Class into JSON using Gson. Gson gson = new Gson(); String json = gson.toJson(chModelArrayList); //here chModelArrayList is a ArrayList<Model> of Model Class Then after you can add this string to SharedPreferences SharedPreferences preferences; //Create Object of SharedPreferences SharedPreferences.Editor editor; //Create Object of SharedPreferences.Editor //initialize SharedPreferences preferences = activity.getPreferences(Context.MODE_PRIVATE); editor = preferences.edit(); //Add-In SharedPreferences editor.putString(key, json); editor.commit(); for your list from SharedPreferences String json = preferences.getString(key, defVal); Gson gson = new Gson(); //Pass Your Model ArrayList in TypeToken Type type = new TypeToken<ArrayList<ChModel>>() {}.getType(); //here you get your list ArrayList<ChModel> switchGroup1 = gson.fromJson(json, type);