Search code examples
javaandroiddatabasesqliteandroid-sqlite

How to create a new table into a database on android studio?


im working on an android project using an sqlite database, after create the database i realized that i need a new table so i try to add it among the others on my SQLiteOpenHelper class

  BaseDeDatos.execSQL("create table viaje(id_viaje integer primary key, tiempo integer, revs integer,  esfzosub integer, esfzobaj integer)");

But when i run the app and press the button my aplication just crashes and gave me the following message:

android.database.sqlite.SQLiteException: no such column: sfzosub (code 1): , while compiling: UPDATE viaje SET sfzosub=?,sfzobaj=?,id_viaje=?,id_categoria=? WHERE codigo=1

i see that the problem is that changes on the database arent made i tried to restart android studio, rebuild the app and i still have the same problem so, how can i do changes to my database?


Solution

  • The big question now is where do you call the creation of the new table? If you do this in

    public void onCreate(SQLiteDatabase db)
    

    Your code won't be executed, as the database already exists!

    To properly handle that, add it to

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(YOUR_STRING);
    

    And then change the version of your Database to a higher number. When you restart the app it will see a new version and run onUpgrade.