我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
我需要在许多地方获得用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?
我不能这样存储它:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
当前回答
如果你想存储你从响应中得到的整个对象,它可以通过这样做来实现,
首先,在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();
这是所有。
希望对你有所帮助。
快乐的编码();
其他回答
下面是我从这里获得的Kotlin Delegated Properties的使用方法,但扩展了它,并允许使用一种简单的机制来获取/设置SharedPreference属性。
对于String, Int, Long, Float或Boolean,它使用标准的SharePreference getter和setter。然而,对于所有其他数据类,它使用GSON序列化为一个String,用于setter。然后为getter反序列化为数据对象。
与其他解决方案类似,这需要在gradle文件中添加GSON作为依赖项:
implementation 'com.google.code.gson:gson:2.8.6'
下面是一个简单的数据类的例子,我们希望能够保存并存储到SharedPreferences:
data class User(val first: String, val last: String)
下面是一个实现属性委托的类:
object UserPreferenceProperty : PreferenceProperty<User>(
key = "USER_OBJECT",
defaultValue = User(first = "Jane", last = "Doe"),
clazz = User::class.java)
object NullableUserPreferenceProperty : NullablePreferenceProperty<User?, User>(
key = "NULLABLE_USER_OBJECT",
defaultValue = null,
clazz = User::class.java)
object FirstTimeUser : PreferenceProperty<Boolean>(
key = "FIRST_TIME_USER",
defaultValue = false,
clazz = Boolean::class.java
)
sealed class PreferenceProperty<T : Any>(key: String,
defaultValue: T,
clazz: Class<T>) : NullablePreferenceProperty<T, T>(key, defaultValue, clazz)
@Suppress("UNCHECKED_CAST")
sealed class NullablePreferenceProperty<T : Any?, U : Any>(private val key: String,
private val defaultValue: T,
private val clazz: Class<U>) : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T = HandstandApplication.appContext().getPreferences()
.run {
when {
clazz.isAssignableFrom(String::class.java) -> getString(key, defaultValue as String?) as T
clazz.isAssignableFrom(Int::class.java) -> getInt(key, defaultValue as Int) as T
clazz.isAssignableFrom(Long::class.java) -> getLong(key, defaultValue as Long) as T
clazz.isAssignableFrom(Float::class.java) -> getFloat(key, defaultValue as Float) as T
clazz.isAssignableFrom(Boolean::class.java) -> getBoolean(key, defaultValue as Boolean) as T
else -> getObject(key, defaultValue, clazz)
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = HandstandApplication.appContext().getPreferences()
.edit()
.apply {
when {
clazz.isAssignableFrom(String::class.java) -> putString(key, value as String?) as T
clazz.isAssignableFrom(Int::class.java) -> putInt(key, value as Int) as T
clazz.isAssignableFrom(Long::class.java) -> putLong(key, value as Long) as T
clazz.isAssignableFrom(Float::class.java) -> putFloat(key, value as Float) as T
clazz.isAssignableFrom(Boolean::class.java) -> putBoolean(key, value as Boolean) as T
else -> putObject(key, value)
}
}
.apply()
private fun Context.getPreferences(): SharedPreferences = getSharedPreferences(APP_PREF_NAME, Context.MODE_PRIVATE)
private fun <T, U> SharedPreferences.getObject(key: String, defValue: T, clazz: Class<U>): T =
Gson().fromJson(getString(key, null), clazz) as T ?: defValue
private fun <T> SharedPreferences.Editor.putObject(key: String, value: T) = putString(key, Gson().toJson(value))
companion object {
private const val APP_PREF_NAME = "APP_PREF"
}
}
注意:您不需要更新密封类中的任何内容。委托的属性是对象/单例的UserPreferenceProperty, NullableUserPreferenceProperty和FirstTimeUser。
为了从SharedPreferences中保存/获取一个新的数据对象,现在只需要添加四行就可以了:
object NewPreferenceProperty : PreferenceProperty<String>(
key = "NEW_PROPERTY",
defaultValue = "",
clazz = String::class.java)
最后,你可以通过使用by关键字来读取/写入SharedPreferences的值:
private var user: User by UserPreferenceProperty
private var nullableUser: User? by NullableUserPreferenceProperty
private var isFirstTimeUser: Boolean by
Log.d("TAG", user) // outputs the `defaultValue` for User the first time
user = User(first = "John", last = "Doe") // saves this User to the Shared Preferences
Log.d("TAG", user) // outputs the newly retrieved User (John Doe) from Shared Preferences
步骤1:在java文件中复制粘贴这两个函数。
public void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
步骤2: 为了节省使用:
setDefaults("key","value",this);
检索使用:
String retrieve= getDefaults("key",this);
你可以通过使用不同的键名来设置不同的共享首选项,比如:
setDefaults("key1","xyz",this);
setDefaults("key2","abc",this);
setDefaults("key3","pqr",this);
如果你的对象很复杂,我建议序列化/XML/JSON,并将这些内容保存到SD卡。你可以在这里找到关于如何保存到外部存储的其他信息: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
// 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'
希望这对你有所帮助:)
在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);