簡體   English   中英

java.util.hashmap無法轉換為java.util.list

[英]java.util.hashmap cannot be cast to java.util.list

我正在嘗試從具有1個鍵的多個值的哈希圖中檢索數據並將其設置為列表視圖,但無法獲取錯誤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);
    }

並檢索值並放入列表視圖

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);

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

Map包裝到List以匹配期望的類型List<? extends Map<String, ?> List<? extends Map<String, ?>了構造函數SimpleAdapter的 List<? 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 });

參考這個例子

您必須更改添加數據順序。 根據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 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM