如何保存 RecyclerView 内容

How to save RecyclerView content

我正在使用 RecyclerView 作为清单,例如可以用作杂货清单,首先用户添加产品(项目)、价格和商店,然后我的应用添加这个 item 对象到我的 ArrayList 适配器中;我的适配器中的每个项目都是一个相对布局,其中包含 3 个用于产品、价格和商店的 TextView。当用户关闭他的设备或关闭应用程序时出现问题:RecyclerView 重置为空。

在 RecyclerView 中保存项目以使其保留的最简单方法是什么?我是否保存在缓存中?

Shared Preferences 要么 SQLite Databases

您需要以某种方式将数据保存到 persistent storage。对于小的东西,最好使用SharedPreferences。然后,当您重新打开应用程序时,将数据从 SharedPreferences 加载到您的 ArrayList,然后填充 RecyclerView.

要使用 SharedPreferences,您需要将数据转换为 String,因为 SharedPreferences 只能处理原始数据类型。将大量数据转换为 String 的最佳方法是将数据转换为 JSONObject,然后将 JSONObject 转换为 String(可以存储在 SharedPreferences).

JSON就像一本字典,它是一种存储键值对的方式。参见 this SO question for more information and some examples of what it looks like. Then search for how to use JSON and Android (or reference the docs)。

编辑: 如果您的 RecyclerView 显示的数据量很简单,您可以将 Set<String> 存储在 SharedPreferences.参见 this relevant documentation.