android - 在 SharedPreferences 中存储数组列表对象

标签 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 个字符串。有什么方法我可以实现。

最佳答案

使用 Gson 库将您的数组或对象转换为 Json,并将您的数据存储为 json 格式的字符串。

保存;

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);

关于android - 在 SharedPreferences 中存储数组列表对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22984696/

相关文章:

php - 始终从 GCM 中的 php(服务器端)获取无效注册

android - java.lang.OutOfMemoryError : bitmap size exceeds VM budget in ListView and lazy loading images 错误

java - 如何保存复选框状态? - 安卓

android - 如何在 SharedPreferences 中存储 Date 对象?

android - 使用 SharedPreferences 在 ListView 中存储复选框的状态

android - 在xml中的单个TextView中添加两个R.id

android - 无法运行已通过Android SDK安装的aapt,这可能是什么原因?

java - 从服务更改另一个类中的 TextView

java - 使用共享首选项来保存一些整数

java - 设置 CountDownTimer 来运行 onDestroy() 的正确方法是什么?