简体   繁体   English

SimpleAdapter在while循环中显示相同的数据

[英]SimpleAdapter show same data in while loop

I add many data to SQLite but my list view show last data inserted only. 我向SQLite添加了许多数据,但是列表视图仅显示最后插入的数据。 all rows have 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. 当我运行此应用程序时,它会在我这样插入SQLi之后显示最后的DBHelper.COL_VEHICLE_TYPEDBHelper.COL_DATE

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

I don't use any update table function in my code. 我在代码中不使用任何更新表功能。 It should show all data from SQLite that are not same values . 它应该显示来自SQLite的所有不相同值的数据。 How should i fix it? 我该如何解决?

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

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. 问题在于, map始终是相同的Map实例 ,而您只是在更改其内容。

 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. 通过在while循环内移动map声明和初始化,可以保证循环中的每次迭代都使用不同的Map实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM