5

我有一个 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);
4

3 回答 3

9

你必须把

     HashMap<String, String> map = new HashMap<String, String>();

在 for 块内

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

于 2013-07-04T03:27:29.113 回答
3

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

于 2013-07-04T03:34:35.053 回答
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);
 }
于 2013-07-04T07:56:28.780 回答