我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
您可以使用以下代码存储类对象,并从共享首选项检索任何对象。
将以下依赖项添加到应用gradle中
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
//Other dependencies of our project
}
在共享pref文件中添加以下代码。
/**
* Saves object into the Preferences.
*
* @param `object` Object of model class (of type [T]) to save
* @param key Key with which Shared preferences to
**/
fun <T> put(`object`: T, key: String) {
//Convert object to JSON String.
val jsonString = GsonBuilder().create().toJson(`object`)
//Save that String in SharedPreferences
preferences.edit().putString(key, jsonString).apply()
}
/**
* Used to retrieve object from the Preferences.
*
* @param key Shared Preference key with which object was saved.
**/
inline fun <reified T> get(key: String): T? {
//We read JSON String which was saved.
val value = preferences.getString(key, null)
//JSON String was found which means object can be read.
//We convert this JSON String to model object. Parameter "c" (of
//type Class < T >" is used to cast.
return GsonBuilder().create().fromJson(value, T::class.java)
}
}
其他回答
你还没有说明在这之后你对prefsEditor对象做了什么,但是为了持久化首选项数据,你还需要使用:
prefsEditor.commit();
我知道这个帖子有点旧了。 但我还是要把这个贴出来,希望它能帮助到一些人。 通过将对象序列化为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)
编码快乐!
在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);
我的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的完整代码//检查使用实例的活动代码
我已经使用jackson来存储我的对象(jackson)。
添加杰克逊库到gradle:
api 'com.fasterxml.jackson.core:jackson-core:2.9.4'
api 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
api 'com.fasterxml.jackson.core:jackson-databind:2.9.4'
我的测试类:
public class Car {
private String color;
private String type;
// standard getters setters
}
Java对象转换为JSON:
ObjectMapper objectMapper = new ObjectMapper();
String carAsString = objectMapper.writeValueAsString(car);
存储在共享首选项中:
preferences.edit().car().put(carAsString).apply();
从共享首选项中恢复:
ObjectMapper objectMapper = new ObjectMapper();
Car car = objectMapper.readValue(preferences.car().get(), Car.class);