SimpleAdapter show same data in while loop

1618 views java
-4

I add many data to SQLi but my list view show last data insert only all row same value.

    public void onResume() {

        super.onResume();

        db = dbHelper.getWritableDatabase();

        String[] queryColumns = new String[]{"_id", DBHelper.COL_VEHICLE_TYPE, DBHelper.COL_OPTION_NAME,DBHelper.COL_DATE };

        cursor = db.query(DBHelper.TABLE_NAME, queryColumns, null,null,
               null,null,null);

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

        while(cursor.moveToNext())
        {

            map.put("vehicle_type", cursor.getString(1));
            map.put("date", cursor.getString(3));
            lst_driver.add(map);
        }

        String[] showColumns = new String[]{"vehicle_type", "date"};
        int[] views = new int[] {R.id.ColType, R.id.ColDate};

        adapter = new SimpleAdapter(DriverActivity.this,lst_driver, R.layout.activity_list_layout, showColumns, views);
        lv_driver.setAdapter(adapter);
}

when I run this app it show last DBHelper.COL_VEHICLE_TYPE and DBHelper.COL_DATE after I insert to SQLi like this.

0
 9-12-2018 
0
 9-12-2018 
0
 9-12-2018 
0
 9-12-2018 

I not use any update table function in my code. It should show all data from SQLi which not same value . How to fix it?

answered question

Did you check your DB, are all values different in it?

2 Answers

7

try this:

HashMap<String,String> map;
while(cursor.moveToNext())
        {
            map = new HashMap<String,String>();
            map.put("vehicle_type", cursor.getString(1));
            map.put("date", cursor.getString(3));
            lst_driver.add(map);
        }

posted this
2

Your problem comes from this snippet. The issue is that map is always the same Map instance, and you're just changing what it holds.

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

while(cursor.moveToNext())
{

    map.put("vehicle_type", cursor.getString(1));
    map.put("date", cursor.getString(3));
    lst_driver.add(map);
}

An easy fix would be to use a different map every time:

while(cursor.moveToNext())
{
    HashMap<String,String> map = new HashMap<String,String>();
    map.put("vehicle_type", cursor.getString(1));
    map.put("date", cursor.getString(3));
    lst_driver.add(map);
}

By moving the map declaration and initialization inside the while loop, you're guaranteeing that each iteration through the loop uses a different Map instance.

posted this

Have an answer?

JD

Please login first before posting an answer.