我保存一個字符串設置在加載到我的監視列表的共享偏好設置中。當用戶點擊一個按鈕時,在電影的頁面中,它將電影的名稱,標題和發佈日期存儲在一個JSON對象中。所有這些都存儲爲字符串。當我嘗試在觀察列表中添加一部電影時,問題仍然存在,每添加一部新電影,最後一部電影被覆蓋,這意味着我一直只能在觀看列表中看到一部電影。共享prefrence覆蓋
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("WatchlistData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
JSONObject obj = new JSONObject();
try {
obj.put("name", name);
obj.put("date", releaseDate);
obj.put("platform", platform);
} catch (JSONException e) {
e.printStackTrace();
}
Set<String> set = new HashSet<String>();
set.add(obj.toString());
editor.putStringSet("setOfStrings", set);
editor.commit(); //saved
}
});
關注預訂片段OnCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_watchlist, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.watchlist);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mWatchlistAdapter = new WatchlistAdapter(getActivity(), loadFromStorage());
mWatchlistAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mWatchlistAdapter);
return view;
}
的loadFromStorage,加載在recyclerview我的XML文件中,這個方法在我的適配器構造函數。
SharedPreferences mPrefs = getActivity().getSharedPreferences("WatchlistData", Context.MODE_PRIVATE);
ArrayList<watchlist> items = new ArrayList<watchlist>();
Set<String> set = mPrefs.getStringSet("setOfStrings", null); //retrieving set of strings
if (set == null){
Toast.makeText(getActivity(), "No data found", Toast.LENGTH_LONG).show();
} else {
//for every string in set
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s); //for every JSONObject String
String name = jsonObject.getString("name");
String date = jsonObject.getString("date");
String platform = jsonObject.getString("platform");
watchlist newGame = new watchlist();
newGame.setGame(name);
newGame.setDate(date);
newGame.setPlatform(platform);
items.add(newGame);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return items;
}
你能給我一個關於在外部存儲中保存爲JSON/XML的教程嗎? –