Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 update the hard-coded values. How could I return all the names of the columns in a table? (Preferably in a String[])

like image 382
Mohit Deshpande Avatar asked Dec 29 '10 01:12

Mohit Deshpande


People also ask

How can I get all data from a table in SQLite?

If you are running the sqlite3 command-line access program you can type ". tables" to get a list of all tables. Or you can type ".

How retrieve data from SQLite database Android and display it in a table?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.

How do I select multiple columns in SQLite?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.


2 Answers

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

like image 155
GSree Avatar answered Oct 12 '22 23:10

GSree


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 * FROM table WHERE ... 

Or if the table is aliased:

SELECT t.* FROM table AS 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:

Cursor c = 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

like image 41
Daniel Trebbien Avatar answered Oct 13 '22 00:10

Daniel Trebbien