Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new table to database after app has executed once

I'm making a simple database in Android. I want to add new table after my code has executed once. Now, whenever i try changing my onCreate() method in EventDataSqlHelper class my app crashes.

This is probably because onCreate() associated with SQLiteOpenHelper is executed only when app is first run and we can't make further modifications in it .

I also tried writing a separate function for adding new table. It worked perfectly on first execution.But since on 2nd exection it will overwrite its previous database, hence it causes app to crash.

Is there any way to add new tables to database if database has already been created?

package org.example.sqldemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class EventDataSQLHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "events.db";
    private static final int DATABASE_VERSION = 1;

    // Table name
    public static final String TABLE = "events";

    // Columns
    public static final String TIME = "time";
    public static final String TITLE = "title";

    public EventDataSQLHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table " + TABLE + "( " + BaseColumns._ID
                + " integer primary key autoincrement, " + TIME + " integer, "
                + TITLE + " text not null);";
        Log.d("EventsData", "onCreate: " + sql);
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    }


}
like image 732
Gaurav Arora Avatar asked Dec 07 '11 05:12

Gaurav Arora


2 Answers

This is what onUpgrade and DATABASE_VERSION is for.

Example:

  • You have a table events, and is executed on phone.
  • Now you decide, you want a new table users.

    1. change DATABASE_VERSION = 2; (this is your version number)
    2. in onCreate() , create all tables (create table events & create table users)
    3. in onUpgrade(), create all tables that changed between version oldVersion and newVersion (create table users)
  • Later if you want to add new tables, increment DATABASE_VERSION again, and create all tables in onCreate, and changes in onUpgrade

like image 75
Daniel Fekete Avatar answered Oct 01 '22 02:10

Daniel Fekete


You could use CREATE TABLE IF NOT EXISTS TABLENAME ... as your query, that wouldn't overwrite your existing table.

like image 27
Arnab Chakraborty Avatar answered Oct 01 '22 03:10

Arnab Chakraborty