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);
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Case 1: The most ideal way to convert an ArrayList into HashMap before Java 8 is through iterating over the given ArrayList using enhanced for-loop and inserting the String as the key and its length as the value into HashMap.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With