我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
您可以使用gson.jar将类对象存储到SharedPreferences中。 你可以从google-gson下载这个罐子
或者在Gradle文件中添加GSON依赖项:
implementation 'com.google.code.gson:gson:2.8.8'
你可以在这里找到最新的版本
创建共享首选项:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
保存:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
检索:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
其他回答
看这里,这可以帮助你:
public static boolean setObject(Context context, Object o) {
Field[] fields = o.getClass().getFields();
SharedPreferences sp = context.getSharedPreferences(o.getClass()
.getName(), Context.MODE_PRIVATE);
Editor editor = sp.edit();
for (int i = 0; i < fields.length; i++) {
Class<?> type = fields[i].getType();
if (isSingle(type)) {
try {
final String name = fields[i].getName();
if (type == Character.TYPE || type.equals(String.class)) {
Object value = fields[i].get(o);
if (null != value)
editor.putString(name, value.toString());
} else if (type.equals(int.class)
|| type.equals(Short.class))
editor.putInt(name, fields[i].getInt(o));
else if (type.equals(double.class))
editor.putFloat(name, (float) fields[i].getDouble(o));
else if (type.equals(float.class))
editor.putFloat(name, fields[i].getFloat(o));
else if (type.equals(long.class))
editor.putLong(name, fields[i].getLong(o));
else if (type.equals(Boolean.class))
editor.putBoolean(name, fields[i].getBoolean(o));
} catch (IllegalAccessException e) {
LogUtils.e(TAG, e);
} catch (IllegalArgumentException e) {
LogUtils.e(TAG, e);
}
} else {
// FIXME 是对象则不写入
}
}
return editor.commit();
}
https://github.com/AltasT/PreferenceVObjectFile/blob/master/PreferenceVObjectFile/src/com/altas/lib/PreferenceUtils.java
使用delegate Kotlin,我们可以轻松地从共享首选项中放置和获取数据。
inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {
val sharedPrefs by lazy { this@sharedPrefs.getSharedPreferences("APP_DATA", Context.MODE_PRIVATE) }
val gson by lazy { Gson() }
var newData: T = (T::class.java).newInstance()
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getPrefs()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.newData = value
putPrefs(newData)
}
fun putPrefs(value: T?) {
sharedPrefs.edit {
when (value) {
is Int -> putInt(key, value)
is Boolean -> putBoolean(key, value)
is String -> putString(key, value)
is Long -> putLong(key, value)
is Float -> putFloat(key, value)
is Parcelable -> putString(key, gson.toJson(value))
else -> throw Throwable("no such type exist to put data")
}
}
}
fun getPrefs(): T {
return when (newData) {
is Int -> sharedPrefs.getInt(key, 0) as T
is Boolean -> sharedPrefs.getBoolean(key, false) as T
is String -> sharedPrefs.getString(key, "") as T ?: "" as T
is Long -> sharedPrefs.getLong(key, 0L) as T
is Float -> sharedPrefs.getFloat(key, 0.0f) as T
is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
else -> throw Throwable("no such type exist to put data")
} ?: newData
}
}
//use this delegation in activity and fragment in following way
var ourData by sharedPrefs<String>("otherDatas")
关于这个问题有很多很好的答案,穆罕穆德·阿米尔·阿里和穆哈默德·埃尔-班纳在Kotlin使用通用方法实现了答案。
为了节省
fun storeObjectInSharedPref(dataObject: Any, prefName: String): Boolean{
val dataObjectInJson = Gson().toJson(dataObject)
prefsEditor.putString(prefName, dataObjectInJson)
return prefsEditor.commit()
}
检索
fun <T> retrieveStoredObject(prefName: String, baseClass: Class<T>): T?{
val dataObject: String? = preferences.getString(prefName, "")
return Gson().fromJson(dataObject, baseClass)
}
要了解Kotlin中的泛型,请访问这里
我已经使用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);
您可以使用gson.jar将类对象存储到SharedPreferences中。 你可以从google-gson下载这个罐子
或者在Gradle文件中添加GSON依赖项:
implementation 'com.google.code.gson:gson:2.8.8'
你可以在这里找到最新的版本
创建共享首选项:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
保存:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
检索:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);