Gather all Strings from SharedPreference getAll() Method?

北慕城南 提交于 2020-01-05 08:27:18

问题


I'm trying to figure out how to set every String and Key name from my app's SharedPreferences using the getAll() method so I can use those values to name populated buttons and assign those buttons to the access the proper string in sharedpreferences to display in a textview.

The problem is I do not know how to save these values to a String or String Array because I haven't ever dealt with maps before.

If anybody could help me store my SharedPreferences keys and string values to a String array for use in my fragment that would be appreciated.

Here is what I have so far:

String[] arrayToStoreStrings;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    SharedPreferences sp = (SharedPreferences) MadlibsSaved.this.getActivity();
    Map<String,?> keys = sp.getAll();

    for(Map.Entry<String,?> entry : keys.entrySet()){
        Log.d("map values",entry.getKey() + ": " + 
                               entry.getValue().toString());            
}

UPDATED with more effort but still getting errors:

BootstrapButton[] loadButtons;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    SharedPreferences sp = null;
    Map<String,?> keys = sp.MadlibsSaved.this.getActivity().getAll();

    for(Map.Entry<String,?> entry : keys.entrySet()){
        Log.d("map values",entry.getKey() + ": " + 
                               entry.getValue().toString());

        while(!(values[i].matches(null))){
            values[i] = entry.getValue().toString();
            i++;
        }
        while(!(key[i].matches(null))){
            key[i] = entry.getKey().toString();
            i++;
        }

 }

    loadButtons = new BootstrapButton[20];

    loadButtons[0] = new BootstrapButton(getActivity());
    loadButtons[0].setText(values[i]);

回答1:


If you want only the String values:

ArrayList<String> strings = new ArrayList<String>();
for(Map.Entry<String,?> entry : keys.entrySet()){
    if (entry.getValue() instanceof String) {
        strings.add((String) entry.getValue());
    }
}
arrayToStoreStrings = strings.toArray(new String[strings.size()]);

If you want to convert every value to a String:

ArrayList<String> strings = new ArrayList<String>();
for(Map.Entry<String,?> entry : keys.entrySet()){
    strings.add(entry.getValue().toString());
}
arrayToStoreStrings = strings.toArray(new String[strings.size()]);

You can do a similar approach for the map keys (as opposed to map values) in a separate array.



来源:https://stackoverflow.com/questions/24718964/gather-all-strings-from-sharedpreference-getall-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!