55

我正在使用自定义适配器扩展光标适配器在列表视图中显示数据,以显示特定的电话号码我已将 id 传递给数据库类中的方法,但它正在显示

errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

在将调试器放置在方法中时,它不会在行之后

num = cursor.getString(cursor.getColumnIndex("ContactNumber"));

任何人都可以帮我解决它。这是代码:

public String getNumberFromId(int id) 
{
    String num;
    db= this.getReadableDatabase();
    Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
    cursor.moveToFirst();
    num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 
    cursor.close();
    db.close();
    return num;
}
4

7 回答 7

112

每当你处理游标时,总是检查 null 并且检查moveToFirst()没有失败。

if( cursor != null && cursor.moveToFirst() ){
    num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
    cursor.close(); 
}

适当放置日志以查看它是返回null还是空游标。根据该检查您的查询。

更新将两个检查放在一个声明中,正如 Jon 在下面的评论中提到的那样。

更新 2close()调用置于有效游标范围内。

于 2012-04-20T10:17:45.353 回答
22

试试这个..这将避免当光标为空时抛出异常..

if(cursor != null && cursor.moveToFirst()){
    num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 
    cursor.close();
}
于 2012-04-20T10:13:44.083 回答
13

取数据前先检查这个Condition

if(cursor!=null && cursor.getCount()>0){
  cursor.moveToFirst();
  num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 
}
于 2012-04-20T10:32:43.527 回答
7

moveToFirst()在尝试从光标读取任何内容之前,请检查 from 的返回值。看起来好像没有返回任何结果。

于 2012-04-20T10:13:09.970 回答
5

Cursor查询s的保存模式是

// just one
Cursor cursor = db.query(...);
if (cursor != null) {
    if (cursor.moveToFirst()) {
        value = cursor.getSomething();
    }
    cursor.close();
}

// multiple columns
Cursor cursor = db.query(...);
if (cursor != null) {
    while (cursor.moveToNext()) {
        values.add(cursor.getSomething());
    }
    cursor.close();
}
于 2012-04-20T10:17:57.277 回答
0

如果人们还在寻找:

而不是搜索"ContactNumber"尝试搜索Phone.NUMBER. 本教程包含更多详细信息的代码:http: //developer.android.com/training/basics/intents/result.html

于 2013-05-18T20:58:35.257 回答
0

尝试卸载应用程序,然后再次对其进行测试...实际上,当应用程序首次安装时,sqlite db 仅创建一次...因此,如果您认为您的逻辑是最新的,那么重新安装应用程序将为您解决问题。!!!!

于 2019-02-21T07:16:55.407 回答