tyczj tyczj - 1 month ago 9
Android Question

cursor index out of bounds "index 0 requested: with size 0"

I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.

i send in a phone number

public String searchNumber(Context context,String number){

ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}


query

public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();

return cur;
}


test search

from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}


if number is not found it should do the else statement but it does not get that far

Answer

Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.

public String searchNumber(Context context,String number){

    ContactDB db = new ContactDB(context);
    db.open();
    Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
        , PHONE_NUMBER + "='" + number + "'",null,null,null,null);
    String test = null;
    if(curs.moveToFirst()) { //edit
        test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
    }
    curs.close();
    db.close();
    return test; // this will be null if the cursor is empty
}

And get rid of the getIdFromPhone() method.

Comments