Android 在 SharedPreferences 中存储数组列表对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22984696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing Array List Object in SharedPreferences
提问by usrNotFound
This method add new object into ArrayList
此方法将新对象添加到 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));
I am trying to add these 3 strings in SharedPrefrences
. Here is my code:
我正在尝试将这 3 个字符串添加到SharedPrefrences
. 这是我的代码:
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
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.
这种方法一次只添加一个字符串,因为我想一次添加 3 个字符串。有什么方法可以实现。
回答by Sinan Kozak
Convert your array or object to Json with Gson library and store your data as String in json format.
使用 Gson 库将您的数组或对象转换为 Json,并将您的数据存储为 json 格式的字符串。
Save;
节省;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
读;
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);
回答by Hari krishna Andhra Pradesh
Store Arraylist Using Shared Preferences
使用共享首选项存储 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();
Retrieve Arraylist from Shared Preferences
从共享首选项中检索 Arraylist
Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample=new ArrayList<String>(set);
回答by usrNotFound
Don't use Hashset
for this. It will change the ordering of Arraylist
. Use Gson
instead.
If you wish to use Hashset
, you will have to serialize and deserialize which will take up resources.
不要Hashset
用于此。它将改变 的顺序Arraylist
。使用Gson
来代替。如果您想使用Hashset
,则必须进行序列化和反序列化,这将占用资源。