Search code examples
androidsqliteandroid-sqlitesqliteopenhelper

Android SQlite - Working with Dynamic tables


I am building an Android native mobile application and I need to create tables dynamically with user input in my Application. By reading the documents, it looks like I cannot use SQLiteOpenHelper since Table needs to be created only in constructor or in onCteate() method. So I created my own utility class with SQLiteDatabase initialised. With this instance, I created a database and a table. When I query for the tables in the DB, I got an error stating java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

How to open and close SQlite database properly without extending SQLiteOpenHelper class . I need to query the data from different activities depends on the need for data. Is there any tutorial available which matches my need ?

To create Database

public static SQLiteDatabase phiDatebase;

public void createOrOpenDatabase(String dbNmae, Context context){
        this.dbName = dbNmae;
        try{
            uuiDatebase = context.openOrCreateDatabase(dbNmae, Context.MODE_PRIVATE, null);
            Log.i("UUI_LOG","DB CREATED");
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }

To create table,

public void createSurveyTable(String tableName, String queryString){
    try{

        uuiDatebase.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(" + queryString + ");");
        Log.i("UUI_LOG", "TABLE CREATED");

    }
    catch (Exception e){
        e.printStackTrace();
    }

}

But when i query for table list, I am getting the error.

Cursor res =  uuiDatebase.rawQuery( "SELECT name FROM sqlite_master WHERE type='table'", null );
res.moveToFirst();

Below is my complete class to Craete DB, Create Tables and get list of tables.

public class UUIDBHelper {

    public static SQLiteDatabase uuiDatebase;
    public static String dbName = "";


    public void createOrOpenDatabase(String dbNmae, Context context){
        this.dbName = dbNmae;
        try{
            uuiDatebase = context.openOrCreateDatabase(dbNmae, Context.MODE_PRIVATE, null);
            Log.i("PHI_LOG","DB CREATED");
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }

    public void createSurveyTable(String tableName, String queryString , boolean isCreate){
        try{
            if(isCreate) {
                uuiDatebase.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(" + queryString + ");");
                Log.i("PHI_LOG", "TABLE CREATED");
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

    public Cursor getAllTables() {

        //SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  uuiDatebase.rawQuery( "SELECT name FROM sqlite_master WHERE type='table'", null );
        res.moveToFirst();

        return res;
    }

    public Cursor getSurveyNames(String tableName) {

        //SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  uuiDatebase.rawQuery( "SELECT survey_name FROM "+tableName+" WHERE id=0", null );
        res.moveToFirst();

        return res;
    }


}

Here is the Logcat result

03-28 13:28:12.922: E/SQLiteDatabase(2837): **android.database.sqlite.SQLiteDatabaseLockedException: database is locked** (code 5): , while compiling: PRAGMA journal_mode
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:634)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:320)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:294)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:215)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1142)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1131)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:261)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at surveytool.uui.com.uuisurveytool.UUIDBHelper.createOrOpenDatabase(UUIDBHelper.java:24)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at surveytool.uui.com.uuisurveytool.ListCreatedSurvey.onResume(ListCreatedSurvey.java:54)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1241)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.Activity.performResume(Activity.java:6023)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2940)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2982)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.os.Looper.loop(Looper.java:135)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at android.app.ActivityThread.main(ActivityThread.java:5221)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at java.lang.reflect.Method.invoke(Native Method)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at java.lang.reflect.Method.invoke(Method.java:372)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-28 13:28:12.922: E/SQLiteDatabase(2837):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Solution

  • Basically, if SQLITE operations were performed without using SQLiteOpenHelper classs, DB needs to be opened and closed manually.

    public static SQLiteDatabase dbInstance ;
    
    dbInstance = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
    

    And close when the transaction is completed.

    dbInstance .close();