Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解析android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0_Java_Android_Sqlite_Cursor - Fatal编程技术网

Java 如何解析android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0

Java 如何解析android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0,java,android,sqlite,cursor,Java,Android,Sqlite,Cursor,我已经寻找了很长时间的解决方案,但仍然找不到一个相关的方法来让它工作。 我在Android studio中的一个外部myDBClass.java中使用了这个方法来查找最后插入的行 public Cursor lastrow() { // TODO Auto-generated method stub try{ SQLiteDatabase db; db = this.getReadableDatabase(); // Read Data

我已经寻找了很长时间的解决方案,但仍然找不到一个相关的方法来让它工作。 我在Android studio中的一个外部myDBClass.java中使用了这个方法来查找最后插入的行

public Cursor lastrow() {
    // TODO Auto-generated method stub
    try{
         SQLiteDatabase db;
         db = this.getReadableDatabase(); // Read Data
         String query = "SELECT ID As _id, Spinpos, Details, Setfor from alarm order by ID DESC limit 1";
         Cursor cursor = db.rawQuery(query, null);
         if(cursor != null)
            {
                cursor.moveToFirst();
                return cursor;
            }
            else
            {
                return null;
            }

         } catch (Exception e) {
           return null;
         }
      }
然后我在MainActivity.java中执行它


它抛出android.database.CursorIndexOutOfBoundsException。请给我一个解决方案

您还需要检查光标是否有结果,如下所示:

如果光标!=null&&cursor.getCount>0

光标被初始化为位置-1,因此当调用moveToNext时,如果光标到达位置0,则返回true,这意味着db至少获取了一个值

用这个

 if(cursor.moveToNext()){

     //database fetched at least one value
 }

嗨@Panczur,我想查询不会返回null。它要么返回游标,要么抛出异常。通过调用ifmoveToFirst{}或ifmoveToNext{},如果游标不为空,则返回true。展示lastcur方法如何,以便我们可以回答?您已经显示了lastrow方法。
 if(cursor.moveToNext()){

     //database fetched at least one value
 }