Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 767
tyczj Avatar asked Mar 15 '11 18:03

tyczj


2 Answers

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.

like image 121
Robby Pond Avatar answered Nov 14 '22 22:11

Robby Pond


While you retrive value you have to use cursor.moveToNext;

if (cursor.moveToFirst()){
   do{
      String data = cursor.getString(cursor.getColumnIndex("data"));
      // do what ever you want here
   }while(cursor.moveToNext());
}
like image 33
Venky Avatar answered Nov 14 '22 20:11

Venky