我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
另一种不使用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();
}
其他回答
我的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的完整代码//检查使用实例的活动代码
如果你的对象很复杂,我建议序列化/XML/JSON,并将这些内容保存到SD卡。你可以在这里找到关于如何保存到外部存储的其他信息: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
您可以使用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);
将数据存储在SharedPreference中
SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();
试试这个最好的方法:
PreferenceConnector.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferenceConnector {
public static final String PREF_NAME = "ENUMERATOR_PREFERENCES";
public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER";
public static final int MODE = Context.MODE_PRIVATE;
public static final String name = "name";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
写入值:
PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish");
并获得价值使用:
String name= PreferenceConnector.readString(this, PreferenceConnector.name, "");