0

i've been having some trouble with sql lite where the database returns only the last value entered times the number of rows it currently has when I query for it.

I'm trying to retrieve the list of locations from a table that holds them.

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

Here is an image of the logcat results 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 Answers1

0

That's because each time you add a location, you also change the value of location previously assigned. Instead, try creating new instance of Location when adding it to the list:

while (cursor.moveToNext()) {
     Location savedLocation = new Location();
     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);
}
Aaron
  • 3,764
  • 2
  • 8
  • 25