[英]How to store ArrayList into sharedPreferences in Android
在我的應用程序中,我想將ArrayList
存儲到sharedPreferences
並在另一個頁面中獲取此列表!
為了存儲這個列表,我使用了這個庫: https://github.com/MrNouri/GoodPrefs
我寫了下面的代碼,但是當得到這些數據時,我不知道如何獲取數據!
我的商店清單代碼:
for (int i : intList) {
stringBuilder.append("ID : ").append(testPlans.get(i).getId())
.append("Type : ").append(testPlans.get(i).getItemType())
.append("Content").append(steps.get(i).getStepData().toString()).append("-");
App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
testPlans.get(i).getItemType(),
steps.get(i).getStepData().toString()));
}
GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
我獲取數據的代碼:
private List<DataItem> storedStepsBodyList = new ArrayList<>();
Toast.makeText(context, ""+
GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
, Toast.LENGTH_SHORT).show();
這個用於獲取列表的庫給了我 2 個構造函數,一個是標簽名稱,第二個值是默認值! (TEST_STEPS_STORED_LIST,)
但我不知道我可以為構造函數的第二項設置默認值!
我寫了這個GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList)
但顯示這個storedStepsBodyList
的錯誤。
我該如何解決?
簡單的方法,您可以使用Gson
庫,將其添加到 build.gradle,它會將您的列表序列化為JSON
並將其保存到SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<Item> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = new Gson().fromJson(json, type);
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.