简体   繁体   中英

SQLite returns only first row through SELECT * Statement

I am saving some records in my sqlite table and records are being saved absolutely fine. Problem comes when I try to retrieve those records. Let's say I have 3 records in my sqlite so when I retrieve those records, it returns me the first record 3 times. Count is correct but why it returns me only first record 3 times?

This is how I am retrieving the records:

public ArrayList<Cursor> getAllBookings() {
        ArrayList<Cursor> bookingsList = new ArrayList<>();
        SQLiteDatabase readableDatabase = this.getReadableDatabase();
        Cursor cursor = readableDatabase.rawQuery("SELECT * FROM " + BOOKING_TABLE, null);
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            bookingsList.add(cursor);
            cursor.moveToNext();
        }

        return bookingsList;
    }

Please note that I have checked the table in Mozilla SQLiteManager and all records are successfully stored.

The problem is that you are adding the cursor itself to your booking list when you should extract and add the values that each cursor row contains.

So if you have a class Booking the method should be declared as

public List<Booking> getAllBookings() {

Also I think it is better to have a do/while loop here and run it until cursor.moveToNext returns false and inside the loop extract all values using getString or similar methods

List<Booking> bookingsList = new ArrayList<>();
//...
do {
    Booking booking = new Booking();
    booking.setSomething(cursor.getString("somethingColumn"));
    //... other columns
    bookingsList.add(booking);
} while (cursor.moveToNext());

If you don't have a custom class then you could use an array or a List for each row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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