在SharedPreferences中存储数组列表对象

时间:2014-04-10 09:59:09

标签: android sharedpreferences

此方法将新对象添加到ArrayList

//get text from textview
time = date.getText().toString();
entry_d = entry.getText().toString();
dayName = day.getText().toString();

arrayList.add( new ArrayObject( dayName, entry_d ,time));

我正在尝试在SharedPrefrences中添加这3个字符串。这是我的代码:

private void savePreferences(String key, String value) {

    SharedPreferences sharedPreferences = PreferenceManager             
                                     .getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
}

此方法一次只添加一个字符串,因为我想一次添加3个字符串。有什么方法我可以实现。

3 个答案:

答案 0 :(得分:69)

使用Gson库将数组或对象转换为Json,并以json格式将数据存储为String。

保存;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();

String json = gson.toJson(arrayList);

editor.putString(TAG, json);
editor.commit();

读取;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, "");
Type type = new TypeToken<List<ArrayObject>>() {}.getType();
List<ArrayObject> arrayList = gson.fromJson(json, type);

答案 1 :(得分:20)

使用共享首选项存储Arraylist

SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
Editor edit=prefs.edit();

Set<String> set = new HashSet<String>();
set.addAll(your Arraylist Name);
edit.putStringSet("yourKey", set);
edit.commit();

从共享首选项中检索Arraylist

Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample=new ArrayList<String>(set);

答案 2 :(得分:0)

请勿使用Hashset。它将改变Arraylist的顺序。请改用Gson。 如果您希望使用Hashset,则必须序列化和反序列化将占用资源。