Skip to content Skip to sidebar Skip to footer

Return All Columns Of A Sqlite Table In Android

The SQLite database table I'm using is subjected to adding columns whenever I need to. I don't want to hard-code the columns at the risk of updating the database and forgetting to

Solution 1:

Best if you use a SQLiteDatabase instance and use query method

SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();

columnNames should have the column names

Solution 2:

You may not need a list of column names.

It seems that you want the list of column names so that you can build up a comma-separated list of columns to select. If this is the case, then where you would normally place the list of column names in your SELECT query, you could instead use an asterisk:

SELECT*FROMtableWHERE ...

Or if the table is aliased:

SELECT t.*FROMtableAS t ...

An asterisk means "all columns".

EDIT: If you really do want a list of column names of a table, then you can use the following code:

Cursorc= db.rawQuery("SELECT * FROM table WHERE 0", null);
try {
    String[] columnNames = c.columnNames();
} finally {
    c.close();
}

Note that you must not modify the returned array of Strings in any way: https://code.google.com/p/android/issues/detail?id=3731

Solution 3:

It is also interesting to note that the query method accept null as input for the column parameters. If you input null, all the columns will be returned.

db.query("Table_name",null,COLUMN_ID + "=" + id,null,null,null,null);

Will return all columns of the line that has the specified id.

You can see the method definition here.

Post a Comment for "Return All Columns Of A Sqlite Table In Android"