我有一个对象的Arraylist。 每次按下按钮,我都会创建一个对象并将其放在ArrayList中。 退出应用程序时,我需要保存此数组列表。当我再次按下按钮时,它应该将新对象添加到保存到共享首选项的现有数组列表中,
我无法存储和接收数组列表。我使用过GSON,但我不太清楚它是如何工作的。
代码段:
public static ArrayList <BookMark> bkmarkList = new ArrayList();
static SharedPreferences keyvalues =
PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
static Editor editor = keyvalues.edit();
final Button bkmarkButton = (Button) view.findViewById(R.id.mark_button);
bkmarkButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
bkmarkButton.setBackgroundResource(R.drawable.bookmarked);
bkmarkButton.setEnabled(false);
bkmarkButton.invalidate();
String wss = data.mWss;
String guid = data.mGuid;
String title = data.mTitle;
//SharedPreferences keyvalues = activity.getSharedPreferences("bookmark_list", Context.MODE_PRIVATE);
//bkmarkList = (ArrayList<BookMark>) ObjectSerializer.deserialize(keyvalues.getString(bookmark_list, ObjectSerializer.serialize(new ArrayList<BookMark>())));
//editor.getStringSet()
Gson gson = new Gson();
editor.putString("bookmark_list", new Gson().toJson(bkmarkList).toString());
if(keyvalues.getString("bookmark_list","")!=null);
{
ArrayList<BookMark> bkMark = new ArrayList<BookMark>();
//bkMark = gson.fromJson("bookmark_list", ArrayList<BookMark>);
//String value = keyvalues.getString("bookmark_list","");
//keyvalues.getStringSet(gson.fromJson(bkmarkList))
//bkmarkList = gson.fromJson(value, "");
}
bkmarkList.add(new BookMark(wss,guid, title));
}
});
答案 0 :(得分:0)
GSON非常易于使用,请看这里: How Android SharedPreferences save/store object
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); 保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
要退却
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);