2013-06-23 41 views
1

我想從1個鍵的多個值的hashmap檢索數據,並將其設置爲一個列表視圖,但即時通訊gettting錯誤java.util.hashmap不能轉換爲java.util.list。 的代碼如下:java.util.hashmap不能轉換爲java.util.list

ListView lv = (ListView)findViewById(R.id.list); 
    //hashmap of type `HashMap<String, List<String>>` 
    HashMap<String, List<String>> hm = new HashMap<String, List<String>>(); 
    List<String> values = new ArrayList<String>(); 
    for (int i = 0; i < j; i++) { 
     values.add(value1); 
     values.add(value2); 
     hm.put(key, values); 
    } 

和檢索值,並把在ListView

ListAdapter adapter = new SimpleAdapter(
         MainActivitty.this, (List<? extends Map<String, ?>>) hm, 
         R.layout.list_item, new String[] { key, 
           value1,value2}, 
         new int[] { R.id.id, R.id.value1,R.id.value2 }); 
       // updating listview 
       lv.setAdapter(adapter); 

我怎樣才能解決這一問題?

回答

2

裹在ListMap相匹配的預期類型的​​構造SimpleAdapterList<? extends Map<String, ?>

ListAdapter adapter = new SimpleAdapter(
         MainActivitty.this, Arrays.asList(hm), 
         R.layout.list_item, new String[] { key, 
         value1,value2}, 
         new int[] { R.id.id, R.id.value1,R.id.value2 }); 

請參閱本example

+0

,這個工作相當fine.thanks –

+0

http://stackoverflow.com /問題/ 17261990 /散列映射值-非存在-所附到列表視圖 –

0

你必須改變你如何添加數據的順序。根據documentation of SimpleAdapter,您必須創建一個映射列表,列表中的每個條目代表一行數據。這些映射必須包含列名稱作爲鍵,列值作爲值。

所以要創建3行3列,你會怎麼做:

List<? extends Map<String, ?>> data = new ArrayList<? extends Map<String, ?>>(); 
for (int i=0; i < 3; i++) { 
    Map<String, String> row = new HashMap<String, String>(); 
    row.put(key, "key in row " + i); 
    row.put(value1, "value1 in row " + i); 
    row.put(value2, "value2 in row " + i); 
    data.add(row); 
} 

然後創建SimpleAdapter實例:

ListAdapter adapter = new SimpleAdapter(
        MainActivitty.this, data, 
        R.layout.list_item, new String[] { key, 
          value1,value2}, 
        new int[] { R.id.id, R.id.value1,R.id.value2 }); 
相關問題