Java CursorIndexOutOfBoundsException是什么意思?
InfoAPI.java 当我点击保存按钮时,它崩溃了。我怎样才能解决这个问题Java CursorIndexOutOfBoundsException是什么意思?,java,android,button,cursor,Java,Android,Button,Cursor,InfoAPI.java 当我点击保存按钮时,它崩溃了。我怎样才能解决这个问题 public long insertTimeSheet(String name,String weather,String date,String status) { database=dbHelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put(MyDa
public long insertTimeSheet(String name,String weather,String date,String status)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Name,name);
values.put(MyDatabaseHelper.Weather,weather);
values.put(MyDatabaseHelper.Date,date);
values.put(MyDatabaseHelper.Status, status);
Cursor cursor = database.rawQuery("SELECT MAX(ID) FROM "+ MyDatabaseHelper.TABLE_INFO, null);
database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
return cursor.getLong(0);
}
LogCat
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
at com.example.project.project.API.InfoAPI.insertTimeSheet(InfoAPI.java:42)
我发布了一个关于外键的问题
A光标IndexOutofBoundsException
表示您试图获取或写入数据的光标当前未定位在有效的结果行。请特别注意,从rawQuery()
获取的光标最初位于第一行的正前方。这在某种程度上是合理的,因为在查询返回零行的情况下,光标只能放在这个位置
您通常会使用光标的定位方法将其移动到要访问的行。为了按顺序处理所有行,通常是moveToNext()
。还有moveToFirst()
,moveToLast()
,moveToPrevious()
,moveToPosition()
,move()
,move()您需要cursor
做什么?为什么不返回database.insert()
返回值?insert()
返回插入行的计数。然后,只需使用返回database.insert(MyDatabaseHelper.TABLE_INFO,null,value)代码>。供您参考:好的,我不明白您的逻辑,如果您需要游标
调用moveToFirst()
@FrankN.Stein,我需要使用return Cursor.getLong(0);?没有。我更新了我的评论。update()
和delete()
也是如此。在哪一行您会得到异常。CursorIndexOutOfBoundsException您可以看到我以前的帖子,我遵循用户Randyka Yudhistra的方法,但得到“CursorIndexOutOfBoundsException”错误。你可以在这里查阅
public long insertTimeSheet(String name,String weather,String date,String status){
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Name,name);
values.put(MyDatabaseHelper.Weather,weather);
values.put(MyDatabaseHelper.Date,date);
values.put(MyDatabaseHelper.Status, status);
database.insert(MyDatabaseHelper.TABLE_INFO, null, values);
Cursor cursor = database.rawQuery("SELECT MAX(ID) FROM "+ MyDatabaseHelper.TABLE_INFO, null);
if(cursor.getCount()>0){
cursor.moveToFirst();
return cursor.getLong(0);
}
return 0;
}