mahmoud elmahgoub
mahmoud elmahgoub

Reputation: 57

Couldn't read row 0, col -1 from CursorWindow. error

I want to make simple recyclerview from external database but the app crashes. This is in the logcat:

Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

DatabaseAccess class:

public class DatabaseAccess {
    private SQLiteDatabase database;
    private SQLiteOpenHelper openHelper;
    private static DatabaseAccess instance;

    private DatabaseAccess (Context context) {
        this.openHelper = new MyDatabase(context);
    }

    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    public void open() {
        this.database = this.openHelper.getWritableDatabase();
    }

    public void close() {
        if (this.database!= null) {
            this.database.close();
        }
    }

    public ArrayList<CAR> getAllCars() {
        ArrayList<CAR> cars = new ArrayList<>();
        Cursor cursor =  database.rawQuery(" SELECT * FROM " + MyDatabase.CAR_TB_NAME, null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
                String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
                String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
                double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));
                CAR c = new CAR(id,model,color,dpl);
                cars.add(c);
            }
            while (cursor.moveToNext());
            cursor.close();
        }
        return  cars;
    }
}

Upvotes: 0

Views: 60

Answers (1)

mahmoud elmahgoub
mahmoud elmahgoub

Reputation: 57

the error disappeared when I corrected that part of code

int id = cursor.getInt(cursor.getColumnIndex(MyDatabase.CAR_CLN_ID));
            String model = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_MODEL));
            String color = cursor.getString(cursor.getColumnIndex(MyDatabase.CAR_CLN_COLOR));
            double dpl = cursor.getDouble(cursor.getColumnIndex(MyDatabase.CAR_CLN_DPL));

to

int id = cursor.getInt(0);
String model = cursor.getString(1);
String color = cursor.getString(2);
double dpl = cursor.getdouble(3);

Upvotes: 1

Related Questions