【发布时间】:2015-08-08 17:38:35
【问题描述】:
我将一个字符串集保存在加载到我的关注列表的共享首选项中。当用户单击电影页面中的按钮时,它会获取电影的名称、标题和发行日期,并将它们存储在 JSON 对象中。所有这些都存储为字符串。当我尝试在监视列表中添加一部电影时,问题仍然存在,我添加的每一部新电影,最后一部电影都会被覆盖,这意味着我的监视列表中始终只能有一部电影。
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;
}
【问题讨论】:
标签: android sharedpreferences android-recyclerview