Reputation: 290
I have
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;
}
}
but the when I run it on an empty database, it crashes.
any suggestions?
the error is:
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
Upvotes: 2
Views: 406
Reputation: 33505
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
I think you need to modify your condition to:
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;
}
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.
Upvotes: 3
Reputation: 582
Well, perhaps dbHelper is not returning a database. You should check again if the database is empty.
public boolean isEmpty()
{
if (database == null) {
database = dbHelper.getReadableDatabase(); // or similar method that
}
if (database != null) {
Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + DatabaseHelper.TABLE_ENCOURAGEMENTS, null);
if (cursor != null) {
return false;
} else {
return true;
}
}
}
Upvotes: 0