1

I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist'. I could run code below while columns exist:

String keywords1={'pesawat','terbang'}; 
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
   // i can do something (no problem)
}

But i have problem when columns name i change on purpose (to check). What should i do to print error message (in android/java way)?

**String keywords2={'psawat','terang'};** 
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table 
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast
Lita
  • 175
  • 1
  • 2
  • 11
  • 1
    Show you table creation code. It appears there's an error. – Phantômaxx Jun 06 '15 at 12:23
  • 1
    First check if cursor c1 or c2 is null or not. If null then print error – Pankaj Jun 06 '15 at 12:26
  • 1
    possible duplicate of [Checking if a column exists in an application database in Android](http://stackoverflow.com/questions/4719594/checking-if-a-column-exists-in-an-application-database-in-android) – Adam S Jun 06 '15 at 12:55

3 Answers3

8

You're looking for getColumnIndex(String columnName).

int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
    // Column doesn't exist
} else {
    ...
}
Adam S
  • 16,144
  • 6
  • 54
  • 81
0

Here's a general method you can use to check whether a particular column exists in a particular table:

public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
                              String tableName,
                              String columnToFind) {
    Cursor cursor = null;

    try {
        cursor = sqLiteDatabase.rawQuery(
                "PRAGMA table_info(" + tableName + ")",
                null
        );

        int nameColumnIndex = cursor.getColumnIndexOrThrow("name");

        while (cursor.moveToNext()) {
            String name = cursor.getString(nameColumnIndex);

            if (name.equals(columnToFind)) {
                return true;
            }
        }

        return false;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
-1

Try this it works fine :)

Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);
Karamsa
  • 27
  • 1
  • 3
  • 1
    This pragma will give you infos about the table. There shouldn't be a Column that is named like the column you are looking for in this cursor. – Janusz Apr 02 '16 at 14:17