>我正在使用SectionedRecyclerView创建购物清单的2个部分,每个项目都有一个复选框,因此一个部分用于未选中的项目,另一个部分用于选中的项目。每个部分都有一个标题和一个列表。我需要保存两个列表的内容。
部分类:
public class HeaderRecyclerViewSection extends StatelessSection{
private String title;
public List<ShoppingItem> list;
public HeaderRecyclerViewSection(String title, List<ShoppingItem> list) {
super(SectionParameters.builder()
.itemResourceId(R.layout.shopping_item)
.headerResourceId(R.layout.section_header)
.build());
this.title = title;
this.list = list;
}
我现在正在尝试保存一个部分。但是当我加载活动时,我收到此错误:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
.
这发生在loadData()
方法的最后一行。
我已经研究了这个错误,但似乎没有什么能解决我的问题。我认为使用 toJson 和 putString 应该可以工作。也许我错误地调用了firstSection.list。
购物清单类:
private RecyclerView sectionHeader;
private SectionedRecyclerViewAdapter sectionAdapter;
HeaderRecyclerViewSection firstSection = new HeaderRecyclerViewSection("Unchecked", getDataSource());
HeaderRecyclerViewSection secondSection = new HeaderRecyclerViewSection("Checked", getDataSource());
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
// shopping list with sections
sectionHeader = (RecyclerView) findViewById(R.id.shopping_listView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ShoppingList.this);
sectionHeader.setLayoutManager(linearLayoutManager);
sectionHeader.setHasFixedSize(true);
sectionAdapter = new SectionedRecyclerViewAdapter();
sectionAdapter.addSection(firstSection);
sectionAdapter.addSection(secondSection);
sectionHeader.setAdapter(sectionAdapter);
loadData();
}
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(firstSection.list);
editor.putString("shopping list", json);
editor.commit();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
List<ShoppingItem> list = new ArrayList<>();
String json = sharedPreferences.getString("shopping list", null);
Type type = new TypeToken<List<ShoppingItem>>() {}.getType();
list = gson.fromJson(json, type);
}
> İ 认为你应该使用
editor.apply()
然后,当您将对象转换为json时,您也应该将类作为参数
toJson(firstSection,HeaderRecyclerViewSection.class);