[英]java.util.hashmap cannot be cast to java.util.list
i'm trying to retrieve data from a hashmap with multiple values for 1 key and set it to a listview but im gettting the error java.util.hashmap cannot be cast to java.util.list. 我正在尝试从具有1个键的多个值的哈希图中检索数据并将其设置为列表视图,但无法获取错误java.util.hashmap不能转换为java.util.list。 The code is as follows:
代码如下:
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);
}
and to retrieve the values and put in a 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);
how can i fix this? 我怎样才能解决这个问题?
Wrap the Map
in a List
to match the expected type List<? extends Map<String, ?>
将
Map
包装到List
以匹配期望的类型List<? extends Map<String, ?>
List<? extends Map<String, ?>
of the constructor SimpleAdapter : 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 });
You must change the order how you add data. 您必须更改添加数据顺序。 According to the documentation of SimpleAdapter , you must create a list of maps, where each entry of the list represents one row of data.
根据SimpleAdapter的文档 ,您必须创建一个地图列表,其中列表的每个条目代表一行数据。 The maps must contain the column names as key, and the column value as value.
映射必须包含列名作为键,并且列值作为值。
So to create 3 rows with 3 columns you would do: 因此,要创建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);
}
Then create your SimpleAdapter instance: 然后创建您的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.