我们需要在许多地方获取用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种情况?
我不能这样存储:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
答案 0 :(得分:447)
您可以使用gson.jar将类对象存储到 SharedPreferences 中。 您可以从google-gson
下载此jar或者在Gradle文件中添加GSON依赖项:
compile 'com.google.code.gson:gson:2.8.5'
创建共享偏好:
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);
答案 1 :(得分:32)
要添加@ MuhammadAamirALi的答案,您可以使用Gson保存和检索对象列表
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();
String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null);
Type type = new TypeToken < List < Connection >> () {}.getType();
List < Connection > connections = new Gson().fromJson(connectionsJSONString, type);
答案 2 :(得分:14)
我知道这个帖子有点老了。
但是我还是要发布这个帖子,希望它可以帮助别人。
我们可以将任何对象的字段存储到共享首选项,方法是将对象序列化为String。
在这里,我使用GSON
将任何对象存储到共享首选项。
将对象保存到首选项:
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
从首选项中检索对象:
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
注意:
请务必在您的游戏中添加compile 'com.google.code.gson:gson:2.6.2'
到dependencies
。
示例:
//assume SampleClass exists
SampleClass mObject = new SampleObject();
//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
正如@Sharp_Edge在评论中指出的那样,上述解决方案不适用于List
。
对getSavedObjectFromPreference()
的签名稍加修改 - 从Class<GenericClass> classType
到Type classType
会使此解决方案一般化。修改了函数签名,
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
用于调用,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
快乐 编码!
答案 3 :(得分:6)
最好是创建一个全局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;
}
答案 4 :(得分:5)
尝试这种最佳方式:
<强> 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, "");
答案 5 :(得分:3)
此后您尚未说明对prefsEditor
对象执行的操作,但为了保留首选项数据,您还需要使用:
prefsEditor.commit();
答案 6 :(得分:2)
请看这里,这可以帮到你:
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();
}
答案 7 :(得分:1)
您可以在不使用任何库的情况下将对象保存在首选项中,首先您的对象类必须实现Serializable:
public class callModel implements Serializable {
private long pointTime;
private boolean callisConnected;
public callModel(boolean callisConnected, long pointTime) {
this.callisConnected = callisConnected;
this.pointTime = pointTime;
}
public boolean isCallisConnected() {
return callisConnected;
}
public long getPointTime() {
return pointTime;
}
}
然后您可以轻松地使用这两种方法将对象转换为字符串,将字符串转换为对象:
public static <T extends Serializable> T stringToObjectS(String string) {
byte[] bytes = Base64.decode(string, 0);
T object = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
object = (T) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
public static String objectToString(Parcelable object) {
String encoded = null;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
encoded = new String(Base64.encodeToString(byteArrayOutputStream.toByteArray(), 0));
} catch (IOException e) {
e.printStackTrace();
}
return encoded;
}
保存:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
prefsEditor.putString("MyObject", objectToString(callModelObject));
prefsEditor.commit();
阅读
String value= mPrefs.getString("MyObject", "");
MyObject obj = stringToObjectS(value);
答案 8 :(得分:1)
以下是我从Kotlin Delegated Properties中学到的here的使用,但进行了扩展,并允许使用一种简单的机制来获取/设置SharedPreference属性。
对于String
,Int
,Long
,Float
或Boolean
,它使用标准的SharePreference getter和setter。但是,对于所有其他数据类,对于设置程序,它使用GSON序列化为String
。然后反序列化为该数据对象,以获取该吸气剂。
与其他解决方案类似,这需要在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"
}
}
注意:您不需要更新sealed class
中的任何内容。委托的属性是对象/单词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
答案 9 :(得分:1)
第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);
答案 10 :(得分:1)
如果你想存储你得到的整个对象,它可以通过做类似的事情来实现
首先创建一个方法,将您的JSON转换为util类中的字符串,如下所示。
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();
}
}
然后在获得响应时调用First方法 第二,当您需要从
等共享偏好中获取数据时String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();
就是这样。
希望它会对你有所帮助。
<强> Happy Coding();
强>
答案 11 :(得分:1)
另一种在不使用Json格式的情况下从android sharedpreferences保存和恢复对象的方法
import os
import sys
import psutil
import tensorflow as tf
def py_funner(x, do_py=True):
'''
this function returns the exact input.
if do_py==True, it passes the data through a python noop using tf.py_func
'''
if do_py:
def py_func(y):
# this is just another noop.
return y
# py_func wraps a python function as a tensorflow op.
return tf.py_func(py_func, [x], [tf.string], stateful=False)[0]
else:
return x
def get_data(do_py=True):
# take the code as input. the effect is way more pronounced on larger files,
# e.g., a tsv that encode image data in base64, as for ms-celeb-1m
in_str = os.__file__
# produce a queue that reads the one file row by row.
input_queue = tf.train.string_input_producer([in_str])
reader = tf.TextLineReader()
ind, row = reader.read(input_queue)
# call the wrapper to either include tf.py_func or not.
return py_funner(row, do_py=do_py)
def main():
# get the current proccess to monitor memory usage
process = psutil.Process(os.getpid())
# execute the same code both with a tf.py_func noop and without it
for tt in [False, True]:
print 'run WITH%s tf.py_func'%('' if tt else 'OUT')
# generate the data queue
data = get_data(do_py=tt)
# start the session and the queue coordinator
sess = tf.Session()
coord = tf.train.Coordinator()
queue_threads = tf.train.start_queue_runners(sess, coord=coord)
# read a lot of the file
max_iter = 50000
for i in range(max_iter):
run_ops = [data]
d = sess.run(run_ops)
mem = process.memory_percent()
print '\r%05d/%d, %.4f%% mem'%(i+1, max_iter, mem),
sys.stdout.flush()
if i%5000==0:
print
print '\n==========================='
if __name__=='__main__':
main()
答案 12 :(得分:0)
如果您的Object很复杂,我建议使用Serialize / XML / JSON并将这些内容保存到SD卡。您可以在此处找到有关如何保存到外部存储的其他信息: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
答案 13 :(得分:0)
有两个文件解决了您关于 sharedpreferences
的所有问题<强> 1)AppPersistence.java 强>
public class AppPersistence {
public enum keys {
USER_NAME, USER_ID, USER_NUMBER, USER_EMAIL, USER_ADDRESS, CITY, USER_IMAGE,
DOB, MRG_Anniversary, COMPANY, USER_TYPE, support_phone
}
private static AppPersistence mAppPersistance;
private SharedPreferences sharedPreferences;
public static AppPersistence start(Context context) {
if (mAppPersistance == null) {
mAppPersistance = new AppPersistence(context);
}
return mAppPersistance;
}
private AppPersistence(Context context) {
sharedPreferences = context.getSharedPreferences(context.getString(R.string.prefrence_file_name),
Context.MODE_PRIVATE);
}
public Object get(Enum key) {
Map<String, ?> all = sharedPreferences.getAll();
return all.get(key.toString());
}
void save(Enum key, Object val) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (val instanceof Integer) {
editor.putInt(key.toString(), (Integer) val);
} else if (val instanceof String) {
editor.putString(key.toString(), String.valueOf(val));
} else if (val instanceof Float) {
editor.putFloat(key.toString(), (Float) val);
} else if (val instanceof Long) {
editor.putLong(key.toString(), (Long) val);
} else if (val instanceof Boolean) {
editor.putBoolean(key.toString(), (Boolean) val);
}
editor.apply();
}
void remove(Enum key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key.toString());
editor.apply();
}
public void removeAll() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
<强> 2)AppPreference.java 强>
public static void setPreference(Context context, Enum Name, String Value) {
AppPersistence.start(context).save(Name, Value);
}
public static String getPreference(Context context, Enum Name) {
return (String) AppPersistence.start(context).get(Name);
}
public static void removePreference(Context context, Enum Name) {
AppPersistence.start(context).remove(Name);
}
}
现在您可以保存,删除或获取类似内容,
<强> -save 强>
AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);
<强> -remove 强>
AppPreference.removePreference(context, AppPersistence.keys.USER_ID);
<强> -get 强>
AppPreference.getPreference(context, AppPersistence.keys.USER_ID);
答案 14 :(得分:0)
将数据存储在SharedPreference
中SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();
答案 15 :(得分:0)
我的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);
。
Full code of my utils //使用活动代码中的示例进行检查
答案 16 :(得分:0)
//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'
hope this helps you :)
答案 17 :(得分:0)
我无法使用接受的答案来跨活动访问“共享首选项”数据。在这些步骤中,为getSharedPreferences提供一个名称以对其进行访问。
在Gradle脚本下的build.gradel(模块:app)文件中添加以下依赖项:
implementation 'com.google.code.gson:gson:2.8.5'
要保存:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("Key", json);
prefsEditor.commit();
要检索其他活动:
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("Key", "");
MyObject obj = gson.fromJson(json, MyObject.class);
答案 18 :(得分:0)
我已经用杰克逊(Jackson)来存储对象(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);
答案 19 :(得分:0)
使用代表团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")
答案 20 :(得分:0)
这么多好的答案,她是我的 2 美分
我更喜欢使用内联函数和老式的 put 和 get value
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()