How does one check if a table exists in an Android SQLite database?
Try this one:
public boolean isTableExists(String tableName, boolean openDb) { if(openDb) { if(mDatabase == null || !mDatabase.isOpen()) { mDatabase = getReadableDatabase(); } if(!mDatabase.isReadOnly()) { mDatabase.close(); mDatabase = getReadableDatabase(); } } String query = "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'"; try (Cursor cursor = mDatabase.rawQuery(query, null)) { if(cursor!=null) { if(cursor.getCount()>0) { return true; } } return false; }}
Although there are already a lot of good answers to this question, I came up with another solution that I think is more simple. Surround your query with a try block and the following catch:
catch (SQLiteException e){ if (e.getMessage().contains("no such table")){ Log.e(TAG, "Creating table " + TABLE_NAME + "because it doesn't exist!" ); // create table // re-run query, etc. }}
It worked for me!