我正在尝试将一些Array
对象保存到SharedPreferences
.
它是如何在我的应用程序上运行的:
我有RecyclerView
包含可点击项目。单击这些项目时,它们将被添加到一个新数组中。新数组显示在另一个视图中。我正在尝试将数组添加到SharedPreferences
片段onDestroyView()
的开头。这意味着当我杀死片段时,数组将保存在SharedPreferences
.
现在使用我的代码,在读取数据时,我只从数组中获取最后一个对象,而不是所有对象。
这是我的代码:
private LightsHistory lightsHistory;
private ArrayList<LightsHistory> lightHistories = new ArrayList<>();
将项目添加到另一个视图:
public void addItemToHistory(int position) {
String title = mLightsArray.get(position).getLampTitle();
String desc = mLightsArray.get(position).getLampDesc();
String imageURL = mLightsArray.get(position).getLampImageUrl();
lightsHistory = new LightsHistory(imageURL, title, desc);
lightHistories.clear();
lightHistories.add(lightsHistory);
for (int j = 0; j < lightHistories.size(); j++) {
if (i == 3) {
i = 0;
}
Glide.with(getContext())
.load(lightHistories.get(j).getmLightsIMG())
.override(150)
.into(historyItemsPH.get(i));
i++;
}
saveToSharedPrefs(lightHistories);
}
保存到 SP
public void saveToSharedPrefs(ArrayList<LightsHistory> lightHistories) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(lightHistories);
editor.putString(TAG, json);
editor.commit();
Log.d(TAG, "saveToSharedPrefs: "+json);
}
从 SP 读取
public void readFromSharedPrefs() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, "");
Type type = new TypeToken<List<LightsHistory>>() {
}.getType();
ArrayList<LightsHistory> arrayList = gson.fromJson(json, type);
if (arrayList != null) {
for (int j = 0; j < lightHistories.size(); j++) {
Log.d(TAG, "readFromSharedPrefs: " + arrayList.get(j).getmLightsTitle()
+ "\n" + arrayList.get(j).getmLightsDesc()
+ "\n" + arrayList.get(j).getmLightsIMG());
}
}
}