程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> sqlite-空數據庫報出錯誤信息

sqlite-空數據庫報出錯誤信息

編輯:編程綜合問答
空數據庫報出錯誤信息
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

謝謝!

最佳回答:


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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved