【发布时间】:2019-03-02 04:21:15
【问题描述】:
我正在处理shared Preferences。基本上,我将ArrayList 保存到shared preferences,它们工作正常。现在我想从Shared preferences 中检索ArrayList,但我得到了空值。 ArrayList 正在从首选项中检索并显示它的大小。但数据未设置为字符串。我如何从共享首选项中检索 ArrayList。
这是我的代码
public void saveRootCategory(List<Category> categories){
preferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
editor = preferences.edit();
editor.putInt("RootCategory",categories.size());
for (int i=0;i<categories.size();i++){
setData(categories.get(i));
}
editor.apply();
}
public void setData(final Category category){
categoryId = category.getId();
categoryName = category.getCategoryName();
editor.putInt("CategoryId",categoryId);
editor.putString("CategoryName",categoryName);
}
public ArrayList<String> getRootCategoy() {
preferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
ArrayList<String> rootCategories = new ArrayList<>();
rootCategories.clear();
int size = preferences.getInt("RootCategory", 0);
for(int i=0;i<size;i++) {
int Id = preferences.getInt("CategoryId" + i,0);
String name = preferences.getString("CategoryName" + i ,"");
rootCategories.add(String.valueOf(Id));
rootCategories.add(name);
}
return rootCategories;
}
【问题讨论】:
标签: android arraylist sharedpreferences