poovi.org poovi.org - 5 months ago 32
Java Question

how to solve this hashmap logical error in android?

I'm facing some known solvable problem but struck out here. In my code, the values are getting stored in ArrayList on the first for loop execution. However, on the 2nd loop and further, the values are overwritten by the final values in the ArrayList. Finally, the lastly entered values are alone getting stored with the number of times of size of the list.

lstall = (ListView)findViewById(R.id.lvall);
sampleArrayList = new ArrayList<HashMap<String, String>>();
ListAdapter sampleListAdapter;
dh = new DBHelper(this);
HashMap<String, String> sampleObjectMap;
List<String> lvall = dh.selectAll();
sampleObjectMap= new HashMap<String, String>();
for(int i=0;i<lvall.size();i++)
{
for (@SuppressWarnings("unused") String sampleObj : lvall)
{
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));

}
sampleArrayList.add(sampleObjectMap);

}


I need to store all the values in a arraylist and display within a list view. Any help is highly appreciated and thanks in advance.

Answer

You're creating a single HashMap<String, String> and repeatedly overwriting the entries within it.

In fact, you're doing that twice as you have a nested for loop for no obvious reason. I believe you want:

for (int i = 0; i < lvall.size(); i++)
{
    HashMap<String, String> sampleObjectMap = new HashMap<String, String>();
    sampleObjectMap.put("title", dh.val1(i));
    sampleObjectMap.put("person", dh.pers(i));
    sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
    sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
    sampleArrayList.add(sampleObjectMap);
}

It also seems odd to use a list's size but not actually use the values within the list... you might want to consider restructuring your code...