我有一个产品列表,我从 web 服务检索,当应用程序第一次打开时,应用程序从 web 服务获取产品列表。我想将此列表保存到共享首选项中。
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;
}
}
如何保存此列表而不是每次都从 web 服务请求?
最佳答案
只能使用原始类型,因为偏好保留在内存中。但是您可以使用 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);
}
}
关于java - 如何将 List<Object> 保存到 SharedPreferences?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107647/