Reputation: 295
i'm working sqlite.i want to check if table is empty.i wrote some code but my code does not working perfect this is a my DatabaseHelper code (function)
public boolean CheckGenderTableEmpty() {
boolean isEmpty = false;
String count = "SELECT * FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
if (mcursor.getCount() != 0) {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e("is not empty", "is not empty");
isEmpty=true;
}
} else {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e(" empty", "empty");
isEmpty=false;
}
}
return isEmpty;
}
as i said my code does not working perfect.first time my table is empty and i can't show log message about empty and i call my function activity like this..
if(db_helper.CheckGenderTableEmpty()==true)
{
Toast.makeText(getApplicationContext(), "is not empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "empty", Toast.LENGTH_SHORT).show();
}
how i can check if database is empty in activity?
if anyone knows solution please help me
Upvotes: 0
Views: 4358
Reputation: 180070
The Android framework has a helper function for this in the DatabaseUtils class:
public boolean CheckGenderTableEmpty() {
return DatabaseUtils.queryNumEntries(db, "Gender") == 0;
}
Upvotes: 1
Reputation: 9996
Use getCount()
method of Cursor
:
public boolean IsTableEmpty(Cursor cursor) {
return !(cursor.getCount() > 0);
}
Upvotes: 1
Reputation: 2815
cursor.moveToFirst(); // Always one row returned.
Then check cursor.getInt (0) == 0
if(cursor.getInt (0) == 0) // Zero count means empty table.
Try this.
Upvotes: -1
Reputation: 5260
you can go with something like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//do accordingly
else
//do accordingly
Upvotes: 0