2011-03-15 125 views
6

当我在数据库中搜索某些内容时,我得到的索引超出了“index 0 requested:with size 0”的错误。我在我的数据库中搜索的项目目前不存在,我知道这一点,但我如何处理该项目不存在的查询。游标索引超出范围“索引0请求:大小为0”

我的电话号码发送

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语句,但是它没有得到那么远

回答

16

Cursor.moveToFirst()如果Cursor为空,则返回false。来自query()调用的返回Cursor永远不会为空,但它可能为空。你永远不会检查游标是否为空。

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()方法。

+0

池塘,我不能摆脱getIDFromPhone的,因为我不能访问的查询,除非我是在数据库类,这是该方法所做的内部。我也得到一个空指针异常这样做你的方式。它会更容易转换为布尔值,因为我需要知道数字是否存在于数据库中 – tyczj 2011-03-16 04:13:33

+0

真棒,感谢罗比,这是超级有用的,得到相同的cur == null问题! :) – Soham 2011-11-04 06:55:54

5

当你retrive价值,你必须使用cursor.moveToNext;

if (cursor.moveToFirst()){ 
    do{ 
     String data = cursor.getString(cursor.getColumnIndex("data")); 
     // do what ever you want here 
    }while(cursor.moveToNext()); 
} 
相关问题