我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
这么多好答案,她是我的2美分
我更喜欢使用内联函数和旧风格的put和get值
object PreferenceHelper {
private const val PREFERENCES_KEY = "MyLocalPreference"
private fun getPreference(context: Context): SharedPreferences {
return context.getSharedPreferences(
PREFERENCES_KEY,
Context.MODE_PRIVATE
)
}
fun setBoolean(appContext: Context, key: String?, value: Boolean?) =
getPreference(appContext).edit().putBoolean(key, value!!).apply()
fun setInteger(appContext: Context, key: String?, value: Int) =
getPreference(appContext).edit().putInt(key, value).apply()
fun setFloat(appContext: Context, key: String?, value: Float) =
getPreference(appContext).edit().putFloat(key, value).apply()
fun setString(appContext: Context, key: String?, value: String?) =
getPreference(appContext).edit().putString(key, value).apply()
// To retrieve values from shared preferences:
fun getBoolean(appContext: Context, key: String?, defaultValue: Boolean?): Boolean =
getPreference(appContext).getBoolean(key, defaultValue!!)
fun getInteger(appContext: Context, key: String?, defaultValue: Int): Int =
getPreference(appContext)
.getInt(key, defaultValue)
fun getString(appContext: Context, key: String?, defaultValue: String?): String? =
getPreference(appContext)
.getString(key, defaultValue)
}
使用
PreferenceHelper.setString(context,"CUSTOMER_NAME", "HITESH")
Toast.makeText(context, "Hello " + PreferenceHelper.getString(context,"CUSTOMER_NAME", "User"), Toast.LENGTH_LONG).show()
其他回答
如果你想存储你从响应中得到的整个对象,它可以通过这样做来实现,
首先,在util类中创建一个将JSON转换为字符串的方法,如下所示。
public static <T> T fromJson(String jsonString, Class<T> theClass) {
return new Gson().fromJson(jsonString, theClass);
}
然后在共享偏好类中执行如下操作,
public void storeLoginResponse(yourResponseClass objName) {
String loginJSON = UtilClass.toJson(customer);
if (!TextUtils.isEmpty(customerJSON)) {
editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
editor.commit();
}
}
然后为getPreferences创建一个方法
public Customer getCustomerDetails() {
String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
if (!TextUtils.isEmpty(customerDetail)) {
return GSONConverter.fromJson(customerDetail, Customer.class);
} else {
return new Customer();
}
}
然后只是调用第一个方法时,你得到的响应和 其次,当你需要从分享偏好中获取数据时
String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();
这是所有。
希望对你有所帮助。
快乐的编码();
将数据存储在SharedPreference中
SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();
您可以使用以下代码存储类对象,并从共享首选项检索任何对象。
将以下依赖项添加到应用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)
}
}
看这里,这可以帮助你:
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
我已经使用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);