1

My cursor is crashing my application with the android database error.

CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

I made another much less optimized slider that scans my database and I find the good value.

public Cursor getAllDataTableStaffDatabase(String table_name){
     this.open();
     Cursor result =this.mDb.rawQuery("SELECT * FROM " + table_name,null);
     return result;// fonctionne très bien
}

public String findNameOfStaffBymail(String mail) {
    String sql = " SELECT  *  FROM " + DatabaseStaffHandler.STAFF_TABLE_NAME + " WHERE " + DatabaseStaffHandler.STAFF_MAIL + " = ? ";
    Cursor result = super.mDb.rawQuery(sql, new String[]{mail});
    Cursor data = super.getAllDataTableStaffDatabase(DatabaseStaffHandler.STAFF_TABLE_NAME);

    String test = result.getString(1); //error

    while (data.moveToNext()) {
        if (data.getString(3).equals(mail)) {
            viewAll();
            return data.getString(1);
        }
    }
}

I would like to retrieve the value name that corresponds to the email address.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98

2 Answers2

0

This usually happens when you do not have the data in your Cursor and you are still trying to access the data. It is similar to the ArrayIndexOutOfBoundsException. I found nothing wrong with your query so far. However, I think you might consider adding null checking in your code which will prevent your application from crashing. Especially in the while loop, you need to put a null check in the condition.

And you need to use the moveToFirst function wherever necessary.

public Cursor getAllDataTableStaffDatabase(String table_name) {
     this.open();
     Cursor result = this.mDb.rawQuery("SELECT * FROM " + table_name,null);
     return result;
}

public String findNameOfStaffBymail(String mail) {
    String sql = " SELECT  *  FROM " + DatabaseStaffHandler.STAFF_TABLE_NAME + " WHERE " + DatabaseStaffHandler.STAFF_MAIL + " = ? ";
    Cursor result = super.mDb.rawQuery(sql, new String[]{mail});
    Cursor data = super.getAllDataTableStaffDatabase(DatabaseStaffHandler.STAFF_TABLE_NAME);

    // Add a null checking here.
    if (result != null) {
        result.moveToFirst();
        String test = result.getString(1);
    }

    if(data != null) data.moveToFirst();

    while (data != null) {
        if (data.getString(3).equals(mail)) {
            viewAll();
            return data.getString(1);
        }

        data.moveToNext();
    }
}

Hope that solves your problem.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
0

Thank you for your reply. I found my problem thanks to you. I wonder if the cursor does not boot at the end. But it is good practice to check if received is not null. Thank you and have a nice day