如何将 List 保存到 SharedPreferences?
2024-05-15

我有一个产品列表,我从网络服务检索该列表,当应用程序第一次打开时,应用程序从网络服务获取产品列表。我想将此列表保存到共享首选项中。

    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;
    }
}

我如何保存此列表而不是每次都从网络服务请求?


只能使用原始类型,因为首选项保留在内存中。但是你可以使用的是使用 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);
     }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 List 保存到 SharedPreferences? 的相关文章

随机推荐