Android의 Shared Preferences에서 객체를 어떻게 저장/저장합니까?
많은 필드가 포함된 여러 장소에서 사용자 개체를 가져와야 합니다.로그인 후 이러한 사용자 개체를 저장/저장하려고 합니다.이런 시나리오를 어떻게 구현할 수 있을까요?
이렇게 저장할 수 없습니다.
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
gson.jar를 사용하여 클래스 개체를 SharedPreferences에 저장할 수 있습니다.이 병은 구글-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);
@Muhammad Aamir에 추가하기ALI의 답변: 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);
나는 이 실이 좀 오래되었다는 것을 압니다.하지만 누군가에게 도움이 되기를 바라며 어쨌든 이것을 게시할 것입니다.개체를 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)
행복해 코딩!
더 나은 것은 글로벌하게 만드는 것입니다.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;
}
다음 방법을 사용해 보십시오.
기본 설정Connector.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, "");
다음 코드를 사용하여 클래스 개체를 저장하고 공유 기본 설정에서 개체를 검색할 수 있습니다.
앱 그라들에 다음 종속성 추가
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)
}
}
위임 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")
당신은 당신이 무엇을 하는지 말하지 않았습니다.prefsEditor
이지만 기본 데이터를 하려면 다음을.
prefsEditor.commit();
라이브러리를 사용하지 않고도 기본 설정에 개체를 저장할 수 있습니다. 먼저 개체 클래스는 Serialable:
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);
승인된 답변을 사용하여 여러 활동에 걸쳐 공유 환경설정 데이터에 액세스하는 데 문제가 발생했습니다.이 단계에서는 getSharedPreferences에 액세스할 이름을 지정합니다.
Gradle Scripts 아래의 build.gradel(Module: 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);
다음과 같은 이점이 있습니다.
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();
}
// 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'
이것이 당신에게 도움이 되길 바랍니다 :)
좋은 대답이 너무 많아서, 그녀는 내 2센트야.
저는 인라인 기능과 오래된 스타일의 풋 앤 겟 밸류를 사용하는 것을 선호합니다.
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()
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);
공유 선호도에 대한 당신의 모든 문제를 해결한 두 개의 파일이 있습니다.
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();
}
}
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);
}
}
이제 저장, 제거 또는 다음과 같은 작업을 수행할 수 있습니다.
-저장
AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);
-제거
AppPreference.removePreference(context, AppPersistence.keys.USER_ID);
-얻기
AppPreference.getPreference(context, AppPersistence.keys.USER_ID);
만약 당신이 응답하는 전체 객체를 저장하고 싶다면, 그것은 다음과 같은 것을 함으로써 달성될 수 있습니다.
먼저 아래와 같이 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();
그게 다야
도움이 되길 바랍니다.
Happy Coding();
다음은 여기서 선택한 Kotlin 위임 속성을 사용하는 방법이지만, 공유 기본 설정 속성을 가져오거나 설정할 수 있는 간단한 메커니즘을 제공합니다.
위해서String
,Int
,Long
,Float
또는Boolean
표준 공유 기본 설정 게터 및 세터를 사용합니다. 다른 클래스에하여 나다모데든이클래의스경 GSON사다같다니로 합니다.String
다음.그런 다음 게터를 위해 데이터 개체로 역직렬화합니다.
다른 솔루션과 마찬가지로 gradle 파일에 GSON을 종속성으로 추가해야 합니다.
implementation 'com.google.code.gson:gson:2.8.6'
다음은 Shared Preferences에 저장하고 저장할 수 있는 간단한 데이터 클래스의 예입니다.
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
.
Shared Preferences(공유 기본 설정)에서 저장/얻기 위해 새 데이터 개체를 설정하는 것은 다음과 같은 네 줄을 추가하는 것만큼 쉽습니다.
object NewPreferenceProperty : PreferenceProperty<String>(
key = "NEW_PROPERTY",
defaultValue = "",
clazz = String::class.java)
마지막으로 다음을 사용하여 공유 기본 설정에 값을 읽고 쓸 수 있습니다.by
키워드:
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
공유 기본 설정에 모델의 배열 목록을 저장하는 방법
이 종속성 추가
implementation 'com.google.code.gson:gson:2.8.8'
그런 다음 Gson을 사용하여 Model Class를 JSON으로 변환한 후에
Gson gson = new Gson(); String json = gson.toJson(chModelArrayList); //here chModelArrayList is a ArrayList<Model> of Model Class
그런 다음 이 문자열을 공유 환경설정에 추가할 수 있습니다.
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();
공유 환경설정의 목록을 확인합니다.
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);
객체가 복잡할 경우 Serialize/XML/JSON을 사용하여 SD 카드에 내용을 저장하는 것이 좋습니다.http://developer.android.com/guide/topics/data/data-storage.html#filesExternal 에서 외장 스토리지에 저장하는 방법에 대한 추가 정보를 찾을 수 있습니다.
Json 형식을 사용하지 않고 Android 공유 환경설정에서 개체를 저장하고 복원하는 다른 방법
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();
}
공유 기본 설정에 데이터 저장
SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).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);
.
활동 코드의 예제를 사용하여 // 내 유틸리티의 전체 코드 확인
저는 제 물건들을 저장하기 위해 잭슨을 사용했습니다.
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
}
JSON에 대한 Java 개체:
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);
이 질문에 대한 많은 훌륭한 답변들, 일반적인 접근법을 사용하여 코틀린에서 Muhammad Aamir Ali & Muhammed El-Banna에 의한 답변의 구현.
보호하기 위해
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)
}
코틀린의 제네릭에 대해 알아보려면 여기를 방문하십시오.
언급URL : https://stackoverflow.com/questions/7145606/how-do-you-save-store-objects-in-sharedpreferences-on-android
'programing' 카테고리의 다른 글
엑셀 VBA의 Rnd()가 정말 이렇게 나쁜가요? (0) | 2023.08.10 |
---|---|
교차 검증 등을 위해 데이터 세트를 교육 및 테스트 데이터 세트로 분할/분할하는 방법은 무엇입니까? (0) | 2023.08.10 |
테이블스페이스 색인 (0) | 2023.08.10 |
속성과 함께 시작된 Spring-boot(프로파일별) 응용 프로그램에서 응용 프로그램 속성 재정의 문제런처 (0) | 2023.08.10 |
C/C++로의 R 컴파일러가 있습니까? (0) | 2023.08.10 |