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

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

问题描述

我使用自定义适配器扩展光标适配器在列表视图中显示数据,以显示特定的电话号码我已经通过ID到数据库类中的一个方法,但它显示

  errorandroid.database.CursorIndexOutOfBoundsException:请求索引0,大小为0 

同时将调试器放在方法中不在行后

  num = cursor.getString .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;
}


解决方案

,ALWAYS检查null并检查 moveToFirst()

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

正确放置日志以查看是否返回 null 或空白游标。根据检查您的查询。



更新将这两个检查都放在单独的语句中,如Jon在下面的注释中所述。



更新2 在有效游标范围内调用 close() / p>

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

解决方案

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

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

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

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

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

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