所以我在主要 Activity 中有一些共同的偏好:
SharedPreferences prefs = this.getSharedPreferences("myFavs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
然后我添加一些生成的字符串作为键值对:
editor.putString(saved,saved);
editor.apply();
在另一个 Activity 中,我希望能够将我保存在共享首选项文件中的所有键值对显示到 ListView 中。
我用过类似的东西:
ListView listView = (ListView) findViewById(R.id.favsList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listlayout, android.R.id.text1, values );
listView.setAdapter(adapter);
之前,但是我不确定如何将所有共享首选项转换为可以放入 ListView 的格式。
P.S 我应该提到我真的只需要一个键或值的列表,因为键和值总是相同的。
我认为这可能已经解决了我的问题:
SharedPreferences prefs = getSharedPreferences("myFavs", 0);
Map<String, String> m = (Map<String, String>) prefs.getAll();
List<String> list = new ArrayList<>(m.values());
这是正确的吗?
最佳答案
如果我理解正确的话,您需要的是检索所有偏好值。
为此你可以使用它;
Map<String,?> allPrefs = prefs.getAll();
for(Map.Entry<String,?> entry : allPrefs.entrySet()){
String key = entry.getKey();
String value = entry.getValue().toString();
}
您可以将值存储到数组中并使用。
更新
更准确地说
public String[] fetchAllPreference(){
String[] values = new String();
int index = 0;
Map<String,?> allPrefs = prefs.getAll();
for(Map.Entry<String,?> entry : allPrefs.entrySet()){
value[index++] = entry.getValue().toString();
}
return values;
}
您可以使用此函数获取所有首选项和可以提供给 Listview 适配器的返回字符串数组
关于java - 获取共享首选项并将它们显示在 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994689/