如何将arraylist中的所有值放入android中的hashmap?

时间:2013-07-04 03:25:29

标签: android arraylist hashmap

我有一个ArrayList,我想将所有数组数据放在我的哈希映射中,但问题是我得到的是数组列表的最后一个索引值。 这是我的代码

ArrayList<String> imagesFileName = new ArrayList<String>();
public String[] filename;

public static final String FILE_NAME = "filename";
public static final String DESCRIPTION = "filename1";
public static final String UPLOADEDBY = "filename2";
public static final String DATE_UPLOAD = "filename3";
public static final String ACTION = "filename4";
public static final String ID = "1";
ArrayList<HashMap<String, String>> mylist;

   filename = new String[imagesFileName.size()];
     for (int i = 0; i < imagesFileName.size(); i++) {
         filename[i] = imagesFileName.get(i);
    }


         mylist = new ArrayList<HashMap<String, String>>();
         HashMap<String, String> map = new HashMap<String, String>();
         for (int i = 0; i < imagesFileName.size(); i++) {
            map.put(FILE_NAME, filename[i]);
            map.put(DESCRIPTION, "desc");
            map.put(UPLOADEDBY, "uploadby");
            map.put(DATE_UPLOAD, "date_upload");
            map.put(ACTION, "delete");
            map.put(ID, "1");
            mylist.add(map);
    }


     adapter = new CustomArrayAdapter(getApplicationContext(), mylist, R.layout.attribute_ireport_list, 
             new String[]{FILE_NAME, DESCRIPTION, UPLOADEDBY, DATE_UPLOAD, ACTION, ID},
             new int[]{R.id.tv_File, R.id.txt_Desc, R.id.tv_UploadedBy, R.id.tv_DateUploaded, R.id.tv_Action, R.id.txt_id}, true);

        lv_iReport.setAdapter(adapter);

3 个答案:

答案 0 :(得分:9)

你必须把

     HashMap<String, String> map = new HashMap<String, String>();
块内的

您只有一个“地图”实例,而您只是更改该地图的值。

答案 1 :(得分:3)

问题是如何使用地图对象。将地图添加到列表时,您不会添加它的新副本。相反,您正在复制对地图的引用。所以你每次都要添加相同的地图。在循环的最后一次运行中,使用数组中最后一个对象的值覆盖映射中的所有值。这就是为什么看起来只添加了最后一个元素。在我写这篇文章时,luisZavaleta刚刚发布了你需要做的事情,所以请听他说。

答案 2 :(得分:2)

 for (int i = 0; i < imagesFileName.size(); i++) {
    HashMap<String, String> map = new HashMap<String, String>();//put in it
    map.put(FILE_NAME, filename[i]);
    map.put(DESCRIPTION, "desc");
    map.put(UPLOADEDBY, "uploadby");
    map.put(DATE_UPLOAD, "date_upload");
    map.put(ACTION, "delete");
    map.put(ID, "1");
    mylist.add(map);
 }