![](/img/trans.png)
[英]Android: Get the entire array the value/key is in ArrayList<HashMap<String, String>>
[英]add the value in Arraylist<string,List<String>> in hashmap android
我必須獲取大量數據。
所以我已經將字符串的數組列表與list。一起使用了,在這里我如何在地圖上添加值。
我用下面的代碼:
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)
我如何清除這些錯誤..pls為我提供了這些解決方案...
在這條線
map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));
您要添加一個字符串而不是列表
此時,您必須創建一個字符串列表,然后將字符串添加到該列表中,並將該列表添加到地圖中。
例如:
List<String> myList= new ArrayList<String>();
myList.add((Element)nl.item(i)).getAttribute("name"));
map.put( KEY_TITLE,myList);
你有一個循環。 我想我知道您要實現的目標,我將更新我的代碼。 這可以幫助您避免覆蓋地圖輸入
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);
}
}
因為String
不是List<String>.
,您會收到該錯誤List<String>.
將地圖聲明更改為HashMap<String, String>
或將您的String
括入List<String>
並將其提供給方法。
您傳遞的密鑰是錯誤的。 您要傳遞一個字符串,您需要傳遞一個字符串列表。 因此,創建一個列表,將要傳遞給哈希映射的值粘貼到列表中,然后將該列表放入哈希映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.