共享preferences存储数组列表对象 [英] Storing Array List Object in SharedPreferences

查看:144
本文介绍了共享preferences存储数组列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法添加新的对象到数组列表

This method add new object into array list

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

我想补充这3个字符串中的共享prefrences。这是我的code:

I am trying to add these 3 string in SharedPrefrences. Here is my code:

private void savePreferences(String key, String value) {

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

此方法仅在一个时间,因为我想一次过加3串添加一个字符串。有没有什么方法,我可以实现。

This method only add one string at a time where as i want to add 3 strings in one go. Is there any method i can implement.

在此先感谢。

推荐答案

您的数组或对象转换成JSON与GSON库和存储JSON格式的数据字符串。

Convert your array or object to Json with Gson library and store your data as String in json format.

保存;

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, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);

这篇关于共享preferences存储数组列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆