sqllite数据库仅返回最后一个值多次

时间:2018-11-21 23:41:44

标签: android sqlite

我在使用sql lite时遇到了一些麻烦,其中数据库仅返回最后输入的值乘以查询时当前具有的行数。

我正在尝试从保存位置的表中检索位置列表。

 public List<Location> getSavedLocations()
{
    List<Location> savedLocations = new ArrayList<>();
    Location savedLocation = new Location();

    Cursor cursor = db.query(
            SLTable.TABLE_SL,
            SLTable.ALL_COLUMNS,
            null,
            null,
            null,
            null,
            null);

    while(cursor.moveToNext())
    {

        savedLocation.setId(cursor.getInt(cursor.getColumnIndex(SLTable.COLUMN_ID)));
        savedLocation.setTitle(cursor.getString(cursor.getColumnIndex(SLTable.COLUMN_TITLE)));
        savedLocation.setLat(cursor.getDouble(cursor.getColumnIndex(SLTable.COLUMN_LAT)));
        savedLocation.setLng(cursor.getDouble(cursor.getColumnIndex(SLTable.COLUMN_LNG)));

        savedLocations.add(savedLocation);
        Log.i("AAA1", savedLocation.getId() + " " + savedLocation.getTitle());

    }

    for(Location l : savedLocations)
    {
        Log.i("AAA2", l.getId() + " " + l.getTitle());
    }


    cursor.close();
    return savedLocations;
}

这是logcat结果的图像 Logcat results

last location entered was 7777 so it's displayed for all of them After i deleted location 7777, it shows the last location before it

1 个答案:

答案 0 :(得分:0)

那是因为每次添加位置时,您还更改了先前分配的位置值。相反,尝试将a的新实例添加到列表中:

b