[英]How to save List<Object> to SharedPreferences?
我有一个产品列表,我从网络服务中检索,当应用程序第一次打开时,应用程序从网络服务中获取产品列表。 我想将此列表保存到共享首选项。
List<Product> medicineList = new ArrayList<Product>();
其中产品类是:
public class Product {
public final String productName;
public final String price;
public final String content;
public final String imageUrl;
public Product(String productName, String price, String content, String imageUrl) {
this.productName = productName;
this.price = price;
this.content = content;
this.imageUrl = imageUrl;
}
}
我如何保存这个列表而不是每次都从 webservice 请求?
只能使用原始类型,因为偏好保留在内存中。 但是您可以使用的是将您的类型与 Gson 序列化为 json 并将字符串放入首选项中:
private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private static SharedPreferences.Editor editor = sharedPreferences.edit();
public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
set(key, json);
}
public static void set(String key, String value) {
editor.putString(key, value);
editor.commit();
}
以下评论来自@StevenTB 的额外镜头
检索
publicList<YourModel> getList(){
List<YourModel> arrayItems;
String serializedObject = sharedPreferences.getString(KEY_PREFS, null);
if (serializedObject != null) {
Gson gson = new Gson();
Type type = new TypeToken<List<YourModel>>(){}.getType();
arrayItems = gson.fromJson(serializedObject, type);
}
}
您可以使用 GSON 来转换 Object -> JSON(.toJSON) 和 JSON -> Object(.fromJSON)。
用你想要的方式定义你的标签(例如):
private static final String PREFS_TAG = "SharedPrefs"; private static final String PRODUCT_TAG = "MyProduct";
获取您对这些标签的 sharedPreference
private List<Product> getDataFromSharedPreferences(){ Gson gson = new Gson(); List<Product> productFromShared = new ArrayList<>(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonPreferences = sharedPref.getString(PRODUCT_TAG, ""); Type type = new TypeToken<List<Product>>() {}.getType(); productFromShared = gson.fromJson(jsonPreferences, type); return preferences; }
设置您的共享首选项
private void setDataFromSharedPreferences(Product curProduct){ Gson gson = new Gson(); String jsonCurProduct = gson.toJson(curProduct); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonCurProduct); editor.commit(); }
如果要保存一系列产品,请执行以下操作:
private void addInJSONArray(Product productToAdd){ Gson gson = new Gson(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonSaved = sharedPref.getString(PRODUCT_TAG, ""); String jsonNewproductToAdd = gson.toJson(productToAdd); JSONArray jsonArrayProduct= new JSONArray(); try { if(jsonSaved.length()!=0){ jsonArrayProduct = new JSONArray(jsonSaved); } jsonArrayProduct.put(new JSONObject(jsonNewproductToAdd)); } catch (JSONException e) { e.printStackTrace(); } //SAVE NEW ARRAY SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonArrayProduct); editor.commit(); }
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
为了保存
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);
正如在接受的答案中所说,我们可以保存对象列表,例如:
public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
set(key, json);
}
public void set(String key, String value) {
if (setSharedPreferences != null) {
SharedPreferences.Editor prefsEditor = setSharedPreferences.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
}
通过使用获取它:
public List<Company> getCompaniesList(String key) {
if (setSharedPreferences != null) {
Gson gson = new Gson();
List<Company> companyList;
String string = setSharedPreferences.getString(key, null);
Type type = new TypeToken<List<Company>>() {
}.getType();
companyList = gson.fromJson(string, type);
return companyList;
}
return null;
}
您目前有两个选择
a) 使用 SharedPreferences
b) 使用 SQLite 并在其中保存值。
如何执行
a) 共享首选项
首先将您的 List 存储为一个 Set,然后在您从 SharedPreferences 读取时将其转换回一个 List。
Listtasks = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(Listtasks);
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putStringSet("tasks_set", tasksSet)
.commit();
然后当你阅读它时:
Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
.getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);
b) SQLite 一个很好的教程: http : //www.androidhive.info/2011/11/android-sqlite-database-tutorial/
所有与 JSON 相关的答案都是好的,但请记住,如果您实现了 java.io.Serializable 接口,Java 允许您序列化任何对象。 通过这种方式,您也可以将其作为序列化对象保存到首选项中。 以下是存储为首选项的示例: https : //gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111我希望这可以帮助您作为一种选择。
对我来说最好的解决方案,我认为你:
private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private SharedPreferences.Editor editor = sharedPreferences.edit();
List<your object> list = new ArrayList<>();
为了保存:
editor.edit().putString("your key name", new Gson().toJson(list)).apply();
忘记:
list = new Gson().fromJson(sharedPreferences.getString("your key name", null), new TypeToken<List<your object class name>>(){}.getType());
好好享受!
首先,您需要创建函数以将数组列表保存到 SharedPreferences。
public void saveListInLocal(ArrayList<ModelName> list, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); }
您需要创建函数以从 SharedPreferences 获取数组列表。
public ArrayList<ModelName> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<ModelName>>() {}.getType();
return gson.fromJson(json, type);
}
如何调用保存和检索数组列表函数。
ArrayList<ModelName> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<ModelName> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
在 SharedPreferences 中,您只能存储原语。
一种可能的方法是您可以使用 GSON 并将值存储到 JSON 中的首选项中。
Gson gson = new Gson();
String json = gson.toJson(medicineList);
yourPrefereces.putString("listOfProducts", json);
yourPrefereces.commit();
您可以使用Gson
,如下所示:
List<Product>
new Gson().toJson(medicineList, new TypeToken<List<Product>>(){}.getType())
将List
转换为Json String
SharePreferences
一样将转换后的字符串保存到SharePreferences
为了重建您的List
,您需要使用Gson
可用的fromJson方法恢复该过程。
在 Kotlin 中获取泛型列表的完美功能
private fun <T : Serializable> getGenericList(
sharedPreferences: SharedPreferences,
key: String,
clazz: KClass<T>
): List<T> {
return sharedPreferences.let { prefs ->
val data = prefs.getString(key, null)
val type: Type = TypeToken.getParameterized(MutableList::class.java, clazz.java).type
gson.fromJson(data, type) as MutableList<T>
}
}
你可以调用这个函数
getGenericList.(sharedPrefObj, sharedpref_key, GenericClass::class)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.