Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all table names in android sqlite database?

I have tried this code

Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'",null); c.moveToFirst(); while(!c.isAfterLast()){     Toast.makeText(activityName.this, "Table Name=> "+c.getString(0),          Toast.LENGTH_LONG).show(); } 

But it throws the error:

"android.database.sqlite.SQLiteException: no such table: sqlite_master(code 1):, while  compiling: SELECT name FROM sqlite_master WHERE type='table'" 

How to fetch all the table names?

like image 916
Sandeep Avatar asked Mar 13 '13 11:03

Sandeep


People also ask

How do I get a list of tables in SQLite database?

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 ". schema" to see the complete database schema including all tables and indices.

How can I see all SQLite databases?

To show all databases in the current connection, you use the . databases command. The . databases command displays at least one database with the name: main .


2 Answers

Checked, tested and functioning. Try this code:

Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);  if (c.moveToFirst()) {     while ( !c.isAfterLast() ) {         Toast.makeText(activityName.this, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show();         c.moveToNext();     } } 

I am assuming, at some point down the line, you will to grab a list of the table names to display in perhaps a ListView or something. Not just show a Toast.

Untested code. Just what came at the top of my mind. Do test before using it in a production app. ;-)

In that event, consider the following changes to the code posted above:

ArrayList<String> arrTblNames = new ArrayList<String>(); Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);      if (c.moveToFirst()) {         while ( !c.isAfterLast() ) {             arrTblNames.add( c.getString( c.getColumnIndex("name")) );             c.moveToNext();         }     } 
like image 155
Siddharth Lele Avatar answered Sep 25 '22 18:09

Siddharth Lele


Change your sql string to this one:

"SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata' order by name"

like image 26
DawnYu Avatar answered Sep 22 '22 18:09

DawnYu