我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
在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);
其他回答
您可以使用以下代码存储类对象,并从共享首选项检索任何对象。
将以下依赖项添加到应用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)
}
}
要添加到@MuhammadAamirALi的答案,您可以使用Gson保存和检索对象列表
保存用户定义对象的列表到SharedPreferences
public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS";
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
User entity = new User();
// ... set entity fields
List<Connection> connections = entity.getConnections();
// convert java object to JSON format,
// and returned as JSON formatted string
String connectionsJSONString = new Gson().toJson(connections);
editor.putString(KEY_CONNECTIONS, connectionsJSONString);
editor.commit();
从SharedPreferences获取用户定义对象的列表
String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null);
Type type = new TypeToken < List < Connection >> () {}.getType();
List < Connection > connections = new Gson().fromJson(connectionsJSONString, type);
您可以使用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);
使用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")
我已经使用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);