Search code examples
androidsqliteandroid-studioandroid-sqlite

How to add a new table in existing Sqlite DB


I have created a DB in sqlite and a table in this DB. now i want to add one more table(posts_table) in this DB. But when I run the app, a new table is not created in the database

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(
                "create table users_table " +
                        "(id integer primary key, username text)"
        );
        sqLiteDatabase.execSQL(
                "create table posts_table " +
                        "(id integer primary key)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion ) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS users_table");
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS posts_table");

        onCreate(sqLiteDatabase);
    }


Solution

  • You need to either uninstall the App (the database file will then be deleted and all current data will be lost) or increase the database version number, in which case the onUpgrade method will be invoked which will delete the tables (if they exist losing all data in the tables) and then invoke the onCreate method.

    • the database version number is typically the 4th parameter passed to SQLiteOpenHelper, although if you are using the constructor for passing open parameters (in which case it is the 3rd parameter) see SQLiteOpenHelper

    the onCreate method is only automatically invoked once for the lifetime of the database so that the database persists.