SharedPreference中的Android列表
我试图在SharedPreferences中编辑List中的值,但有些问题是错误的。
我的SharedPreference是:
public class StepsData { static SharedPreferences data; static SharedPreferences.Editor editor; static final int VALUE_KEY = 0; static final List LIST_KEY= new Vector(); }
我使用SharedPref:
StepsData.data = getApplicationContext().getSharedPreferences("userData", MODE_PRIVATE); StepsData.editor = StepsData.data.edit();
如果我想编辑或从VALUE_KEY获取值,一切正常:
int step = StepsData.data.getInt(String.valueOf(VALUE_KEY), 0); editor.putInt(String.valueOf(VALUE_KEY), 0).apply();
但我使用List时遇到问题,我获取值的代码是:
List myList = (List) data.getStringSet(String.valueOf(LIST_KEY),null);
并删除:
List clearList = new Vector(); editor.putStringSet(String.valueOf(LIST_KEY), (Set) clearList).apply();
但是有一个NullPointerException。 在SharedPreference的List上使用“.clear()”之类的东西的最佳方法是什么?如何从这个List和大小中获取值?
如果要在SharedPreference中存储List对象,请使用gson库。 它将用于将列表对象转换为json格式并将该json字符串存储到sharedPref中。
首先在gradle文件中包含此行(app level)
编译’com.google.code.gson:gson:2.4′
下面的代码是将Type设置为List
Type listType = new TypeToken>(){}.getType(); Gson gson = new Gson();
现在创建列表对象并使用gson对象和类型转换为json字符串格式
List myList = new ArrayList<>(); //add elements in myList object String jsonFormat = gson.toJson(myList,listType); //adding to sharedPref editor.put("list",jsonFormat).apply();
现在从sharedPref获取值并将json字符串转换回List对象。
//this line will get the json string from sharedPref and will converted into object of type list(specified in listType object) List list = gson.fromJson(sharedPref.get("list",""),listType); //now modify the list object as par your requirement and again do the same step of converting that list object into jsonFormat.
为什么使用list?(包含重复元素)
从共享首选项中获取所有元素
Set set = preference.getStringSet("key", null); //Set the values Set set = new HashSet (); set.addAll(listOfExistingScores); preferenceEditor.putStringSet("key", set); preferenceEditor.commit();
如果你必须使用列表检查这个链接也https://gist.github.com/cr5315/6200903
以下内容:
全局声明myList
:
ArrayList myList = new ArrayList ();
设定值:
for (int i = 0; i < totalSize; i++) { PreferenceManager.getDefaultSharedPreferences(this) .edit() .putString("number" + i, value + "").commit(); }
为了获得价值:
for (int i = 0; i < totalSize; i++) { myList.add(PreferenceManager.getDefaultSharedPreferences(this) .getString("number" + i, "0")); }
注意: - totalSize
是数组的大小