猿问

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

我向 SQLite 添加了许多数据,但我的列表视图仅显示最后插入的数据。所有行都具有相同的值。


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

}

当我运行这个应用程序时,它会在我像这样插入到 SQLi 后显示最后一个DBHelper.COL_VEHICLE_TYPE和DBHelper.COL_DATE。


0

 9-12-2018 

0

 9-12-2018 

0

 9-12-2018 

0

 9-12-2018 

我的代码中没有使用任何更新表函数。它应该显示来自 SQLite 的所有值不同的数据。我该如何解决?


RISEBY
浏览 222回答 2
2回答

千万里不及你

尝试这个:HashMap<String,String> map;while(cursor.moveToNext())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map = new HashMap<String,String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put("vehicle_type", cursor.getString(1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put("date", cursor.getString(3));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lst_driver.add(map);&nbsp; &nbsp; &nbsp; &nbsp; }

收到一只叮咚

你的问题来自这个片段。问题是map总是相同的 Map instance,而您只是在更改它所拥有的内容。HashMap<String,String> map = new HashMap<String,String>();while(cursor.moveToNext()){&nbsp; &nbsp; map.put("vehicle_type", cursor.getString(1));&nbsp; &nbsp; map.put("date", cursor.getString(3));&nbsp; &nbsp; lst_driver.add(map);}一个简单的解决方法是每次使用不同的地图:while(cursor.moveToNext()){&nbsp; &nbsp; HashMap<String,String> map = new HashMap<String,String>();&nbsp; &nbsp; map.put("vehicle_type", cursor.getString(1));&nbsp; &nbsp; map.put("date", cursor.getString(3));&nbsp; &nbsp; lst_driver.add(map);}通过map在while循环内移动声明和初始化,您可以保证循环中的每次迭代都使用不同的Map实例。
随时随地看视频慕课网APP

相关分类

Java
我要回答