我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
我已经使用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);
其他回答
// SharedPrefHelper is a class contains the get and save sharedPrefernce data
public class SharedPrefHelper {
// save data in sharedPrefences
public static void setSharedOBJECT(Context context, String key,
Object value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(value);
prefsEditor.putString(key, json);
prefsEditor.apply();
}
// get data from sharedPrefences
public static Object getSharedOBJECT(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(key, "");
Object obj = gson.fromJson(json, Object.class);
User objData = new Gson().fromJson(obj.toString(), User.class);
return objData;
}
}
// save data in your activity
User user = new User("Hussein","h@h.com","3107310890983");
SharedPrefHelper.setSharedOBJECT(this,"your_key",user);
User data = (User) SharedPrefHelper.getSharedOBJECT(this,"your_key");
Toast.makeText(this,data.getName()+"\n"+data.getEmail()+"\n"+data.getPhone(),Toast.LENGTH_LONG).show();
// User is the class you want to save its objects
public class User {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private String name,email,phone;
public User(String name,String email,String phone){
this.name=name;
this.email=email;
this.phone=phone;
}
}
// put this in gradle
compile 'com.google.code.gson:gson:2.7'
希望这对你有所帮助:)
看这里,这可以帮助你:
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
关于这个问题有很多很好的答案,穆罕穆德·阿米尔·阿里和穆哈默德·埃尔-班纳在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中的泛型,请访问这里
我的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的完整代码//检查使用实例的活动代码
更好的方法是创建一个全局Constants类来保存键或变量以获取或保存数据。
要保存数据,请调用此方法保存来自任何地方的数据。
public static void saveData(Context con, String variable, String data)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
prefs.edit().putString(variable, data).commit();
}
用它来获取数据。
public static String getData(Context con, String variable, String defaultValue)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, defaultValue);
return data;
}
像这样的方法就可以了
public static User getUserInfo(Context con)
{
String id = getData(con, Constants.USER_ID, null);
String name = getData(con, Constants.USER_NAME, null);
if(id != null && name != null)
{
User user = new User(); //Hope you will have a user Object.
user.setId(id);
user.setName(name);
//Here set other credentials.
return user;
}
else
return null;
}