我必须获取数据列表。
所以我使用了带有列表的字符串数组列表。这里我如何在 map 上添加值。
我使用了以下代码:
static final String KEY_TITLE = "Category";
static final String KEY_ARTICLE = "article";
static final String KEY_IMAGE = "image";
final ArrayList<HashMap<String, List<String>>> songsList = new ArrayList<HashMap<String, List<String>>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TITLE);
NodeList nl1 = doc.getElementsByTagName(KEY_ARTICLE);
NodeList nl2 = doc.getElementsByTagName(KEY_IMAGE);
System.out.println(nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
//System.out.println(nl.getLength());
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));
for (int j = 0; j < nl1.getLength(); j++) {
map.put( KEY_ARTICLE,((Element)nl1.item(j)).getAttribute("title"));
map.put( KEY_IMAGE,((Element)nl2.item(j)).getAttribute("url"));
}
songsList.add(map);
}
在这些 (map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));)
行上出现以下错误:
The method put(String, List<String>) in the type HashMap<String,List<String>> is not applicable for the arguments (String, String)
我怎样才能清除这些错误..请为我提供这些问题的解决方案...
最佳答案
在这一行
map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));
您要添加一个字符串而不是列表
此时您必须创建一个字符串列表,并将您的字符串添加到其中,并在列表中添加到您的 map 。
例如:
List<String> myList= new ArrayList<String>();
myList.add((Element)nl.item(i)).getAttribute("name"));
map.put( KEY_TITLE,myList);
你有一个循环。我想我知道你想要实现什么我会更新我的代码。这可以帮助您避免覆盖 map 输入
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for(int i = 0; i < nl.getLength(); i++) {
String name = (Element) nl.item(i)).getAttribute("name");
populateMap(map, name, KEY_TITLE);
for(int j = 0; j < nl1.getLength(); j++) {
String title=(Element) nl1.item(j)).getAttribute("title");
populateMap(map, title, KEY_ARTICLE);
String url=(Element) nl2.item(j)).getAttribute("url");
populateMap(map, url, KEY_IMAGE);
}
songsList.add(map);
}
方法 populateMap()
void populateMap(HashMap<String, List<String>> map, String value, String key) {
List<String> myList;
if(!map.containsKey(key)) {
myList = new ArrayList<String>();
myList.add(value);
map.put(key, myList);
} else {
myList = map.get(key);
myList.add(value);
}
}
关于java - 在 hashmap android 中添加 Arraylist<string,List<String>> 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15738659/