NewDroidDev
NewDroidDev

Reputation: 1686

How to put all value in arraylist to hashmap in android?

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);

Upvotes: 5

Views: 26047

Answers (3)

Winnie
Winnie

Reputation: 769

 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);
 }

Upvotes: 2

Jeff Swenson
Jeff Swenson

Reputation: 31

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.

Upvotes: 3

luisZavaleta
luisZavaleta

Reputation: 1168

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.

Upvotes: 9

Related Questions