如何保存RecyclerView内容

时间:2015-08-07 01:25:43

标签: android android-recyclerview recycler-adapter

我使用RecyclerView作为清单,可以用作购物清单,例如,首先用户添加产品(商品),价格和商店,然后我的应用添加此date/employee对象进入我的ArrayList适配器;我的适配器中的每个项目都是一个相对布局,包含3个TextViews,用于产品,价格和商店。当用户关闭他的设备或关闭应用程序时会出现问题:RecyclerView重置为空。

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

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

You will need to save the data to persistent storage in some way. For something small, it would be best to use SharedPreferences. Then, when you re-open the app, load the data from SharedPreferences into your ArrayList, then populate the RecyclerView.

To use SharedPreferences you will need to convert your data into a String, because SharedPreferences can only handle primitive data types. The best way to convert lots of data to a String is by converting the data into a JSONObject, then that JSONObject into a String (which can be stored in SharedPreferences).

JSON is like a dictionary, it's a way to store Key-Value pairs. See 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).

EDIT: If your RecyclerView is showing a simple amount of data, you may be able to store a Set<String> in your SharedPreferences. See this relevant documentation.