I have an ArrayList and I want to put all the array data in my hash map but the problem is all I get is the last index value of the array list. Here's my code
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);
-
1luisZavaleta's answer is correct, but you're still abusing/misusing a Map when you should really be using a POJO.Matt Ball– Matt Ball2013年07月04日 03:35:26 +00:00Commented Jul 4, 2013 at 3:35
-
@MattBall why this should be considered abuse of the map?Sebastialonso– Sebastialonso2016年06月04日 20:19:31 +00:00Commented Jun 4, 2016 at 20:19
3 Answers 3
You must put
HashMap<String, String> map = new HashMap<String, String>();
inside the for block
You have only one instance of "map" and you're only changing the value of that map.
Comments
The issue is how you use the map object. When you add the map to the list you are not adding a new copy of it. Instead you are copying the reference to the Map. So really you are adding the same map every time. On the last run of the loop you overwrite all the values in the map with the values of the last object in your array. That is why it looks like only the last element is added. As I write this luisZavaleta just posted what you need to do, so listen to him.
Comments
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);
}