我有一个产品列表,我从webservice检索,当应用程序第一次打开时,应用程序从webservice获取产品列表。我要将此列表保存到共享首选项。
List<Product> medicineList = new ArrayList<Product>();
其中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请求?
发布于 2015-01-23 18:27:14
只能使用原语类型,因为首选项保存在内存中。但是你可以使用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的以下评论中的额外镜头
检索
public List<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);
}
}
发布于 2017-07-18 15:21:04
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
为了保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
For get
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
发布于 2018-07-05 17:13:46
正如接受答案中所说的,我们可以保存对象列表,如下所示:
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;
}
https://stackoverflow.com/questions/28107647
复制相似问题