【发布时间】:2015-05-25 13:15:44
【问题描述】:
我正在构建一个 Android 应用程序。我想在首选项中存储一组字符串,以便根据他们的登录信息跟踪谁使用了该应用程序。
我不想使用数据库,所以我知道我应该使用 SharedPreferences 来存储登录人员的列表。我希望能够重置此列表,以便将个人登录数据保留为字符串,而不是因为 StringSets 不是一个选项。使用单独的字符串意味着我必须保留这些字符串的另一个列表,以便我可以在需要时清理它们。 StringSet 更容易维护。
这是我到目前为止所做的:
//this is my preferences variable
SharedPreferences prefs = getSharedPreferences("packageName", MODE_PRIVATE);
//I create a StringSet then add elements to it
Set<String> set = new HashSet<String>();
set.add("test 1");
set.add("test 2");
set.add("test 3");
//I edit the prefs and add my string set and label it as "List"
prefs.edit().putStringSet("List", set);
//I commit the edit I made
prefs.edit().commit();
//I create another Set, then I fetch List from my prefs file
Set<String> fetch = prefs.getStringSet("List", null);
//I then convert it to an Array List and try to see if I got the values
List<String> list = new ArrayList<String>(fetch);
for(int i = 0 ; i < list.size() ; i++){
Log.d("fetching values", "fetch value " + list.get(i));
}
但是,事实证明Set<String> fetch 为空,并且我遇到空指针异常,这可能是因为我没有正确存储或获取我的 StringSet。
【问题讨论】:
-
您在将字符串集放入首选项后忘记了 apply()。