光标索引越界"指数0要求:大小为0" [英] cursor index out of bounds "index 0 requested: with size 0"

查看:144
本文介绍了光标索引越界"指数0要求:大小为0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到光标索引越界索引0要求:大小为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.

我发送一个电话号码

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;
}

查询

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;
}

测试搜索

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

如果没有找到一些它应该做的else语句,但是它没有得到那么远

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

推荐答案

Cursor.moveToFirst()返回false如果光标是空的。从查询()调用返回的指针永远不会为空,但它可能是空的。你永远不会检查是否光标是空的。

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
}

和摆脱getIdFromPhone()方法。

And get rid of the getIdFromPhone() method.

这篇关于光标索引越界"指数0要求:大小为0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆