Gather all Strings from SharedPreference getAll()

2019-07-26 04:07发布

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条回答
欢心
2楼-- · 2019-07-26 04:45

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.

查看更多
登录 后发表回答