[英]Storing ArrayList go objects in sharedpreference
I have an Arraylist of objects. 我有一个对象的数组列表。 Each time I press a button, I create an object and place it in the ArrayList. 每次按下按钮时,都会创建一个对象并将其放置在ArrayList中。 I need to save this array list when I exit the app. 退出应用程序时,我需要保存此数组列表。 When I come and again press the button, it should add a new object to the existing array list saved to the Shared Preference, 当我再次按下按钮时,它应该将一个新对象添加到保存到“共享首选项”的现有阵列列表中,
I am not able to store and receive the array list. 我无法存储和接收阵列列表。 I used GSON but I am not very clear how it works. 我使用了GSON,但是我不清楚它是如何工作的。
Code Snippet: 代码段:
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));
}
});
GSON is very easy to use, look here: How Android SharedPreferences save/store object GSON非常易于使用,请看这里: Android SharedPreferences如何保存/存储对象
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); To Save 保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
To Retreive 回归
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.