SQLite, how to get all table names in database?

22,515

Solution 1

Just did a quick test in the SQLite Manager plugin in FireFox with the SQLite db i'm working with and the query you're using does return the table names. Are you creating the tables correctly and have you tested the exist to your expectations?

To iterate through, do something like:

    if (c.moveToFirst())
    {
        while ( !c.isAfterLast() ){
           dirArray.add( c.getString( c.getColumnIndex("name")) );
           c.moveToNext();
        }
    }

Solution 2

try this code

final ArrayList<String> dirArray = new ArrayList<String>();

SqlHelper sqlHelper = new SqlHelper(this, "TK.db", null, 1);
SQLiteDatabase DB = sqlHelper.getWritableDatabase();
Cursor c = DB.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
while(c.moveToNext()){
   String s = c.getString(0);
   if(s.equals("android_metadata"))
   {
     //System.out.println("Get Metadata");
     continue;
   }
   else
   {
      dirArray.add(s);
   }
 }
Share:
22,515
Roger
Author by

Roger

Updated on July 17, 2022

Comments

  • Roger
    Roger almost 2 years

    What do you think would be the right way to get all table names' from a database and add them to a list?

    Right now got that far:

    final ArrayList<String> dirArray = new ArrayList<String>();
    
    SqlHelper sqlHelper = new SqlHelper(this, "TK.db", null, 1);
    SQLiteDatabase DB = sqlHelper.getWritableDatabase();
    Cursor c = DB.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    
    c.moveToFirst();
    while (c.isAfterLast() == false) {
       dirArray.add("n" + c.getColumnIndex("name"));
       c.moveToNext();
     }
    c.close();
    

    But it outputs some "android_metadata" instead of my table name's. So guess there's something wrong with the query.

    Thanks!

  • Roger
    Roger over 12 years
    Yes, now seems to work, only outputs the first one as "android_metadata", do I just ignore it?
  • SBerg413
    SBerg413 over 12 years
    Yeah, put something in to ignore the first row.. you could even put a c.moveToNext() right before the while() loop OR explicitly check for it.