问题描述
所以我的主要活动有一些共同的偏好:
So I have some shared preferences in my main activity:
SharedPreferences prefs = this.getSharedPreferences("myFavs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
然后我将一些生成的字符串添加为键值对:
And I add some generated strings as a key value pair:
editor.putString(saved,saved);
editor.apply();
在另一个活动中,我希望能够将共享首选项文件中保存的所有键值对显示到ListView中.
In another activity I would like to be able to display all the key value pairs I have saved in my shared preferences file into a ListView.
我曾经使用过类似的东西:
I have used things like:
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的格式.
before, however I am not sure how to get all my shared preferences into a format that I can put into a ListView.
P.S我应该提到,我实际上只需要一个键或值的列表,因为键和值始终相同.
P.S I should have mentioned I only really need a list of either keys or values as the key and the value are always the same.
我认为这可能已经解决了我的问题:
I think this might have solved my problem:
SharedPreferences prefs = getSharedPreferences("myFavs", 0);
Map<String, String> m = (Map<String, String>) prefs.getAll();
List<String> list = new ArrayList<>(m.values());
这正确吗?
推荐答案
如果我理解正确,那么您需要检索所有首选项值.
if I understood in correct sense, what you need is to retrieve all preference values.
为此,您可以使用它;
for that you can use this ;
Map<String,?> allPrefs = prefs.getAll();
for(Map.Entry<String,?> entry : allPrefs.entrySet()){
String key = entry.getKey();
String value = entry.getValue().toString();
}
您可以将值存储到数组中并使用.
you can store the values to an array and use.
更新
更精确
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;
}
您可以使用此功能获取所有首选项和返回的String数组,这些数组可以提供给Listview适配器
you can use this function for getting all the preference and the returned String array you can provide to your Listview adapter
这篇关于获取共享的首选项并将其显示在列表视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!