如何保存列表&LT;对象&gt;为共享preferences? [英] How to save List<Object> to SharedPreferences?
本文介绍了如何保存列表&LT;对象&gt;为共享preferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的产品,这是我从web服务检索列表中,当应用程序被打开一次,应用程序会从Web服务产品清单。我要救这个名单共享preferences。
I have a list of products, which i retrieve from webservice, when app is opened for first time, app gets product list from webservice. I want to save this list to shared preferences.
List<Product> medicineList = new ArrayList<Product>();
其中,产品类:
where Product class is:
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;
}
}
我怎么能拯救这个名单不是从web服务每次请求?
how i can save this List not requesting from webservice each time?
推荐答案
它只能使用基本类型,因为preference保持在内存中。但是你可以用的是序列化的类型与GSON成JSON并把串入preferences:
It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:
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();
}
这篇关于如何保存列表&LT;对象&gt;为共享preferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文