強大な 強大な - 1 month ago 16
Android Question

Android with Sqlite - How to check if table exist and if empty

I want to show an alertbox if the table does not exist or the table content is empty.

To check if the table is empty I'm using:

cCheckDB = db.rawQuery("SELECT COUNT(*) FROM " + MainActivity.TABLE_NAME +"", null);

if (cCheckDB != null) {
cCheckDB.moveToFirst();

if (cCheckDB.getInt (0) == 0) {
// EMPTY
}
}


But how to wrap this in an "if table exist"? What is the best way?

I know both ways to check if a table exist or to check if there is content in it. But I want to use the checks in a meaningful and way and not in single query if this is possible - that's my question.

Answer

Hope,This will be helpful to you. It's working well!!!

public boolean isTableExists(String tableName, boolean openDb) {
    if(openDb) {
        if(mDatabase == null || !mDatabase.isOpen()) {
            mDatabase = getReadableDatabase();
        }

        if(!mDatabase.isReadOnly()) {
            mDatabase.close();
            mDatabase = getReadableDatabase();
        }
    }

    Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
    if(cursor!=null) {
        if(cursor.getCount()>0) {
                            cursor.close();
            return true;
        }
                    cursor.close();
    }
    return false;
}