biscuitstack biscuitstack - 5 months ago 13
Android Question

Passing an SQLite database delete function a table name as a String in Android

If I run:

void deleteTableRecords() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ALBUMS,null,null);
db.close();
}


I get my intended result. However, if I run:

void deleteTableRecords(String tableName) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(tableName,null,null);
db.close();
}


with a call of
deleteTableRecords("TABLE_ALBUMS")
I get a crash and told that:

android.database.sqlite.SQLiteException: no such table: TABLE_ALBUMS


What should I be passing a table name as if not a string?

Answer

TABLE_ALBUMS is the name of your variable. Its value is most probably something else.

I guess you assigned a value to TABLE_ALBUMS, for example:

private static final String TABLE_ALBUMS = "someValue";

In this case you need to pass the actual value, not the name of the variable:

deleteTableRecords("someValue");

A better approach is to make it a public constant:

public class DbHelper {
    public static final String TABLE_ALBUMS = "someValue";

    // ...

}

So you can access it in a static way:

deleteTableRecords(DbHelper.TABLE_ALBUMS);
Comments