gpt4 book ai didi

android - 游标索引越界 "index 0 requested: with size 0"

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:08 24 4
gpt4 key购买 nike

当我在数据库中搜索某些内容时,出现游标索引越界“请求索引 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 语句,但它不会走那么远

最佳答案

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

关于android - 游标索引越界 "index 0 requested: with size 0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5316336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com