【问题标题】:App crashes if SQLite cursor has no results如果 SQLite 游标没有结果,应用程序崩溃
【发布时间】:2016-08-10 05:13:16
【问题描述】:

我有一个使用游标运行 SQlite 查询的应用程序。

    public Cursor totaltrips(){
    Cursor cursor = database.rawQuery("SELECT * AS TTotal FROM " + DatabaseHelper.TABLE_NAME, null);
    return cursor;
}

结果存储到一个最多包含 5 个值的 Arraylist 中。如果数据库中没有记录,则应用程序崩溃。如果我有一个或多个数据库条目,它工作正常。有谁知道当没有数据库条目时如何阻止它崩溃?

 // get column value
    if (Distance.moveToNext())
        result = String.valueOf(Distance.getDouble(Distance.getColumnIndex("myTotal")));

    tnmView.setText(result);

    List<String> distancearray = new ArrayList<String>();
    Cursor cursor =  dbManager.totaldistance();


    do{
        distancearray.add(cursor.getString(1));
    }while ((cursor.moveToNext()));
    ttrips = cursor.getCount();
    Log.i("Graph", "TTRIPS = " + ttrips);

    // Be sure here to have at least the 5 desired elements into the list
    while(distancearray.size() < 5){
        distancearray.add("0");
    }

应用程序因错误而崩溃

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

上线

do{
        distancearray.add(cursor.getString(1));
    }while ((cursor.moveToNext()));

【问题讨论】:

  • 在此之前你可以检查 cursor.getCount() > 0 ...
  • 只需将您的 do while 循环添加到 if/else 语句 if(curser.getCount()&gt;0){ //do-while loop here}
  • 在循环之前检查 cursor.getCount() > 0

标签: android sqlite arraylist android-sqlite


【解决方案1】:

检查光标是否真的有结果,例如尝试这样的事情:

int numResults = cursor.getCount();
if (numResults > 0) {
    do {
        distancearray.add(cursor.getString(1));
    } while ((cursor.moveToNext()));
}

【讨论】:

  • 这应该是答案
【解决方案2】:

替换

do{
    distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));

if (cursor != null) {
    while (cursor.moveToNext()) {
        distancearray.add(cursor.getString(1));
    }
    cursor.close();
}

【讨论】:

    【解决方案3】:

    检查游标是否为空且具有多个值。使用后关闭游标。

    if(cursor!=null&&cursor.getCount()>0){
    cursor.moveToFirst();
    while(cursor.hasNext()){
    
    //do stuff here
    }
    
    cursor.close();
    }
    

    【讨论】:

    • 这将跳过第一行。
    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多