android.database.CursorIndexOutOfBoundsException:请求索引 0,大小为 0 [英] android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

查看:37
本文介绍了android.database.CursorIndexOutOfBoundsException:请求索引 0,大小为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing

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

在方法中放置调试器时,它不会跟随该行

while placing debugger in the the method it is not going after the line

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

谁能帮我解决一下.这是代码:

Can any one help me to solve it. This is the code:

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

推荐答案

无论何时处理游标,始终检查 null 并检查 moveToFirst() 不会失败.

Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.

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

适当放置日志以查看它是返回 null 还是空游标.根据那个检查你的查询.

Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.

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

Update Put both the checks in a single statement as mentioned by Jon in the comment below.

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

Update 2 Put the close() call within the valid cursor scope.

这篇关于android.database.CursorIndexOutOfBoundsException:请求索引 0,大小为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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