Is there a nice way in Android to see if a column exists in a table in the application database? (I know there are questions similar to this one already, but there don't seem to be any that are Android specific.)
cursor.getColumnIndex(String columnName)
returns -1 if, the column doesn't exist. So I would basically perform a simple query like "SELECT * FROM xxx LIMIT 0,1" and use the cursor to determine if the column, you are looking for, exists
OR
you can try to query the column "SELECT theCol FROM xxx" and catch an exception
My function based on @martinpelants answer:
private boolean existsColumnInTable(SQLiteDatabase inDatabase, String inTable, String columnToCheck) { Cursor mCursor = null; try { // Query 1 row mCursor = inDatabase.rawQuery("SELECT * FROM " + inTable + " LIMIT 0", null); // getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1 if (mCursor.getColumnIndex(columnToCheck) != -1) return true; else return false; } catch (Exception Exp) { // Something went wrong. Missing the database? The table? Log.d("... - existsColumnInTable", "When checking whether a column exists in the table, an error occurred: " + Exp.getMessage()); return false; } finally { if (mCursor != null) mCursor.close(); } }
Simply call:
boolean bla = existsColumnInTable(myDB,"MyTable","myColumn2check");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With