在Android中,我们能否将一个类的对象存储在共享偏好中并在以后检索该对象?
如果可能,如何实现?如果不可能,还有哪些其他可能性可以实现?
我知道序列化是一种选项,但我正在寻找使用共享偏好的可能性。
在Android中,我们能否将一个类的对象存储在共享偏好中并在以后检索该对象?
如果可能,如何实现?如果不可能,还有哪些其他可能性可以实现?
我知道序列化是一种选项,但我正在寻找使用共享偏好的可能性。
我们可以使用Gson来实现这个。
从GitHub下载可运行的代码。
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
< p >获取数据Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
GSON的最新版本可以从github.com/google/gson下载。
如果您正在使用Gradle/Android Studio,请在build.gradle
的依赖部分中添加以下内容:
implementation 'com.google.code.gson:gson:2.6.2'
String json = gson.toJson(MyObject);
。 - Ahmed Hegazy mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
ed.putString(key, new String(out.toByteArray()));
ed.commit();
} catch (IOException e) {
e.printStackTrace();
}
当我们需要从Preference中提取Object时,可以使用以下代码:
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
if (bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
ObjectInputStream in;
in = new ObjectInputStream(base64InputStream);
MyObject myObject = (MyObject) in.readObject();
我有同样的问题,这是我的解决方案:
我有一个名为MyClass
的类和一个ArrayList<MyClass>
,我想将它们保存到共享首选项中。起初,我添加了一个将其转换为JSON对象的方法到MyClass
中:
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("id", this.id);
obj.put("name", this.name);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
接下来是保存对象 ArrayList<MyClass> items
的方法:
SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
SharedPreferences.Editor editor = mPrefs.edit();
Set<String> set= new HashSet<String>();
for (int i = 0; i < items.size(); i++) {
set.add(items.get(i).getJSONObject().toString());
}
editor.putStringSet("some_name", set);
editor.commit();
这里是检索对象的方法:
public static ArrayList<MyClass> loadFromStorage() {
SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
ArrayList<MyClass> items = new ArrayList<MyClass>();
Set<String> set = mPrefs.getStringSet("some_name", null);
if (set != null) {
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s);
Long id = jsonObject.getLong("id"));
String name = jsonObject.getString("name");
MyClass myclass = new MyClass(id, name);
items.add(myclass);
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
使用Gson库:
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
店铺:
Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
检索:
String json = getPrefs().getUserJson();
implementation 'com.google.code.gson:gson:2.8.0'
然后在您的代码中,例如Kotlin中的字符串/布尔值对:
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
添加到 SharedPrefs:
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
现在来检索数据:
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects. Basically, it's using GSON mechanism to store objects.
To save object into prefs:
User user = new User();
user.setName("Felipe");
user.setAge(22);
user.setActive(true);
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();
And to retrieve it back:
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);
通用的共享首选项(CURD) SharedPreference:使用简单的 Kotlin 类以值-键对的形式存储数据。
var sp = SharedPreference(this);
存储数据:
为了存储字符串、整数和布尔类型的数据,我们有三种方法,它们拥有相同的名称但不同的参数(方法重载)。
save("key-name1","string value")
save("key-name2",int value)
save("key-name3",boolean)
获取数据: 要检索存储在SharedPreferences中的数据,请使用以下方法。
sp.getValueString("user_name")
sp.getValueInt("user_id")
sp.getValueBoolean("user_session",true)
sp.clearSharedPreference()
移除特定数据:
sp.removeValue("user_name")
常用的共享偏好设置类
import android.content.Context
import android.content.SharedPreferences
class SharedPreference(private val context: Context) {
private val PREFS_NAME = "coredata"
private val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
//********************************************************************************************** save all
//To Store String data
fun save(KEY_NAME: String, text: String) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putString(KEY_NAME, text)
editor.apply()
}
//..............................................................................................
//To Store Int data
fun save(KEY_NAME: String, value: Int) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(KEY_NAME, value)
editor.apply()
}
//..............................................................................................
//To Store Boolean data
fun save(KEY_NAME: String, status: Boolean) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putBoolean(KEY_NAME, status)
editor.apply()
}
//********************************************************************************************** retrieve selected
//To Retrieve String
fun getValueString(KEY_NAME: String): String? {
return sharedPref.getString(KEY_NAME, "")
}
//..............................................................................................
//To Retrieve Int
fun getValueInt(KEY_NAME: String): Int {
return sharedPref.getInt(KEY_NAME, 0)
}
//..............................................................................................
// To Retrieve Boolean
fun getValueBoolean(KEY_NAME: String, defaultValue: Boolean): Boolean {
return sharedPref.getBoolean(KEY_NAME, defaultValue)
}
//********************************************************************************************** delete all
// To clear all data
fun clearSharedPreference() {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.clear()
editor.apply()
}
//********************************************************************************************** delete selected
// To remove a specific data
fun removeValue(KEY_NAME: String) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.remove(KEY_NAME)
editor.apply()
}
}
Blog: https://androidkeynotes.blogspot.com/2020/02/shared-preference.html
1. Create Public class
public class Prefs {
//Single Instance object
private static Prefs instance = null;
private SharedPreferences sharedPreference = null;
//Single Instance get
public static Prefs getPrefInstance() {
if (instance == null)
instance = new Prefs();
return instance;
}
@SuppressWarnings("static-access")
private void openPrefs(Context context) {
sharedPreference = context.getSharedPreferences(Const.PREFS_FILENAME,
context.MODE_PRIVATE);
}
public void setValue(Context context, String key, String value) {
openPrefs(context);
SharedPreferences.Editor prefsEdit = sharedPreference.edit();
prefsEdit.putString(key, value);
prefsEdit.commit();
prefsEdit = null;
sharedPreference = null;
}
public String getValue(Context context, String key, String value) {
openPrefs(context);
String result = sharedPreference.getString(key, value);
sharedPreference = null;
return result;
}
public void remove(Context context, String key) {
openPrefs(context);
SharedPreferences.Editor prefsEditor = sharedPreference.edit();
prefsEditor.remove(key).commit();
prefsEditor = null;
sharedPreference = null;
}
}
2. If you want to store value in SharedPreferences with below line.
Prefs.getPrefInstance().setValue(MainActivity.this, Const.GCM_ID, token);
3. If you want to get the value from SharedPreferences.
Prefs.getPrefInstance().getValue(context, Const.GCM_ID, "");
4. If you want to remove the value from SharedPreferences.
Prefs.getPrefInstance().remove(context, Const.GCM_ID);