List always returns only the first row of the bank sqlite [closed]

0

I have a list, which shows all sqlite bank data, image path, latitude and longitude, but in the list only changes the image path, latitude and longitude always stays the first record.

public List<Foto> todasFotos(){

    List<Foto> listaFotos = new ArrayList<Foto>();

    SQLiteDatabase db =  getReadableDatabase();

    String sqlTodasFotos =  "SELECT * FROM imagens";

    Cursor c = db.rawQuery(sqlTodasFotos,null);

    if (c.moveToNext()) {
        do {
            Foto foto = new Foto();
            foto.setId(c.getInt(0));
            foto.setCaminho_foto(c.getString(1));
            foto.setLatitude(c.getDouble(2));
            foto.setLongitude(c.getDouble(3));

            listaFotos.add(foto);
        } while (c.moveToNext());
    }
    db.close();
    return listaFotos;
}
    
asked by anonymous 27.09.2016 / 16:59

2 answers

3

Use moveToFirst() . Considering SQLiteDataBase it is said that:

  

A Cursor object, which is positioned before the first entry.

moveToFirst() does two things:

  • Lets you test whether the query returned an empty set;
  • Moves the cursor to the first result (when the device is not empty).
  • Considering moveToNext() :

    while (cursor.moveToNext());
    

    The cursor starts before the first line of the result, so in the first iteration it moves to the first result if it exists. If the cursor is empty, or the last line has already been processed, then the loop will exit neatly.

    The end result would look like this:

    if (c.moveToFirst()) {
            do {
                Foto foto = new Foto();
                foto.setId(c.getInt(0));
                foto.setCaminho_foto(c.getString(1));
                foto.setLatitude(c.getDouble(2));
                foto.setLongitude(c.getDouble(3));
    
                listaFotos.add(foto);
            } while (c.moveToNext());
    }
    

    Details

    27.09.2016 / 18:53
    1

    Look like this:

    public List<Foto> todasFotos(){
    
        List<Foto> listaFotos = new ArrayList<Foto>();
    
        SQLiteDatabase db =  getReadableDatabase();
    
        String sqlTodasFotos =  "SELECT * FROM imagens";
    
        Cursor c = db.rawQuery(sqlTodasFotos,null);
        cursor.moveToFirst();
    
         if (!cursor.isAfterLast()) {
                   do {
                       Foto foto = new Foto();
                       foto.setId(c.getInt(0));
                       foto.setCaminho_foto(c.getString(1));
                       foto.setLatitude(c.getDouble(2));
                       foto.setLongitude(c.getDouble(3));
    
                        listaFotos.add(foto);
                     }
                      while (cursor.moveToNext());
    
            }
    
        db.close();
        return listaFotos;
    }
    
        
    27.09.2016 / 18:49