Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...