for_2012 2013-04-09 05:25 采纳率: 0%
浏览 2187
已采纳

空数据库报出错误信息

public boolean isEmpty()
{
    if (database == null) {
        database = dbHelper.getReadableDatabase(); // or similar method that   
    }
    Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + DatabaseHelper.TABLE_ENCOURAGEMENTS, null);
    if (cursor != null) {
        return false;
    } else {
        return true;
    }
}

将上面这段代码在一个空数据库中运行时报错,信息如下:

java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:2144)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, 
with a size of 0

谢谢!

  • 写回答

1条回答

  • luhuajcdd 2013-04-09 06:02
    关注
    public boolean isEmpty() {
       int count = -1;
       if (cursor != null && cursor.moveToFirst()) {
          count = cursor.getInt(0);
          if (count > 0) {
             return false;
          }
          else {
             return true;
          }
       }
       return true;
    }
    

    Explanation:

    moveToFirst() is handy method that returns false if Cursor is empty. Checking whether Cursor is assigned to NULL isn't enough. You need to call it always you want to check status of your Cursor because also each Cursor is implicitly positioned before first row so you need to call it always.

    Since you are selecting COUNT(*) so it always return at least one row with count value. You need to check this value whether is greather than zero or not. If yes, db is not empty.

    问题原址:http://stackoverflow.com/questions/15888695/checking-for-an-empty-database-raises-an-error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?