aperture
aperture

Reputation: 2895

android array from shared preferences

I'm trying to iterate over a collection of shared preferences, and generate an ArrayList of HashMaps, but having an issue.

SharedPreferences settings = getSharedPreferences(pref, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");

and then I was thinking something along the lines of:

final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
SharedPreferences settings = getSharedPreferences(pref, 0);
Map<String, ?> items = settings.getAll();
for(String s : items.keySet()){
    HashMap<String,String> temp = new HashMap<String,String>();
    temp.put("key", s);
    temp.put("value", items.get(s));
    LIST.add(temp);
}

This gives the following error:

The method put(String, String) in the type HashMap<String,String> is not applicable for the arguments (String, capture#5-of ?)

Is there a better way to do this?

Upvotes: 1

Views: 8975

Answers (2)

aperture
aperture

Reputation: 2895

Hache had the correct idea. An Object is not a String, so .toString() was necessary.

final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
SharedPreferences settings = getSharedPreferences(pref, 0);
Map<String, ?> items = settings.getAll();
for(String s : items.keySet()){
    HashMap<String,String> temp = new HashMap<String,String>();
    temp.put("key", s);
    temp.put("value", items.get(s).toString());
    LIST.add(temp);
}

Upvotes: 5

Hache
Hache

Reputation: 449

Change

 HashMap<String,String> temp = new HashMap<String,String>();
 final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();

to

 HashMap<String,?> temp = new HashMap<String,?>();
 final ArrayList<HashMap<String,?>> LIST = new ArrayList<HashMap<String,?>>();

and it should work. You're not putting an String but an object this causes the error

Upvotes: 2

Related Questions