android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
将调试器放在方法中时它不在行
之后 double lans = c.getDouble(c.getColumnIndex(LAN));
double lons = c.getDouble(c.getColumnIndex(LON));
任何人都可以帮我解决它
public Locationxy getData(int id , DataBaseHelper dbHelper ) {
SQLiteDatabase dbo = dbHelper.getReadableDatabase();
Locationxy locationxy=new Locationxy();
String[] coulmns = new String[]{BumpID, LAN, LON};
String[] args = new String[]{String.valueOf(id)};
Cursor c = dbo.query(TABLE_BUMPS, coulmns, BumpID + "=?",args, null, null, null, null);
if ((c !=null ) && c.getCount()>0 )
c.moveToFirst();
double lans = c.getDouble(c.getColumnIndex(LAN));
double lons = c.getDouble(c.getColumnIndex(LON));
locationxy = new Locationxy(lans, lons);
return locationxy ;
} }
答案 0 :(得分:1)
试试这个:
if ((c !=null ) && c.moveToFirst() && c.getColumnCount()>2){
double lans = c.getDouble(c.getColumnIndex(LAN));
double lons = c.getDouble(c.getColumnIndex(LON));
locationxy = new Locationxy(lans, lons);
}
要考虑的要点:
你已经把" if"没有括号,所以即使光标为空,也会调用第二行(设置了lons)。
c.getCount()> 0不是必需的,只需调用c.moveToFirst()就足以检查光标是否大于0。
getColumnCount()> 2检查光标是否有必要的列(查看代码看起来像光标有3列,所以我检查它是否比2更好)
答案 1 :(得分:-1)
请注意不带{}的if语句。在这里你只是在c.moveToFirst()
上做了这个条件。
查询后,返回的游标start at the position -1。因此,如果光标的计数等于0,则永远不会调用cursor.moveToFirst。
实现代码的好方法是:
Cursor c = null;
try {
c = dbo.query...
if (c != null && c.moveToFirst()) {
//Here your cursor is at the first position is not empty
double lans = c.getDouble(c.getColumnIndexOrThrow(LAN));
double lons = c.getDouble(c.getColumnIndexOrThrow(LON));
locationxy = new Locationxy(lans, lons);
}
} catch (Exception e) {
//Log.e(); log of any exception;
} finally {
//don't forget to close your cursor.
if (c != null) {
c.close();
}
}
return locationxy;
修改强> 您可以尝试使用getColumnIndexOrThrow来确保列的名称是正确的。