所以,我有一个由JSON Parsing创建的ListView,我希望一旦从ListView中选择一个项目添加到另一个ArrayList,我使用HashMap,因为它是一组数据。问题是,如果我选择一个它工作正常,但是一旦我选择了第二个,那么我的ArrayList将具有SECOND一次两次,如果我再次执行第三个三次,依此类推。我附上下面的代码部分,任何帮助将不胜感激。
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Toast.makeText(getApplicationContext(),
"Bookmarked",
Toast.LENGTH_LONG)
.show();
//adding the data from the list view to the HashMap object
HashMap<String, String> obj = (HashMap<String, String>) adapter.getItemAtPosition(position);
String name = (String) obj.get("name");
String rating = (String) obj.get("rating");
String summary = (String) obj.get("summary");
String date = (String) obj.get("publ. date");
String type = (String) obj.get("type");
String suggested_link = (String) obj.get("suggested_link_text");
String link = (String) obj.get("link");
bookmarked.put("rating", rating);
bookmarked.put("name", name);
bookmarked.put("summary", summary);
bookmarked.put("publ. date", date);
bookmarked.put("type", type);
bookmarked.put("suggested_link_text", suggested_link);
bookmarked.put("link", link);
//the ArrayList that contains the HashMap data
selected.add(bookmarked);
Log.v("Selected: ", selected.toString());
}});
答案 0 :(得分:0)
这是因为您在每次点击时都会覆盖bookmarked
对象,并且您每次都会将同一个对象添加到列表中。
解决方案是每次都创建一个新的bookmarked
对象:
HashMap<String, String> bookmarked = new HashMap<String, String>();
bookmarked.put("rating", rating);
bookmarked.put("name", name);
bookmarked.put("summary", summary);
bookmarked.put("publ. date", date);
bookmarked.put("type", type);
bookmarked.put("suggested_link_text", suggested_link);
bookmarked.put("link", link);