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) {
}
}
This is what onUpgrade
and DATABASE_VERSION
is for.
Example:
events
, and is executed on phone.Now you decide, you want a new table users
.
DATABASE_VERSION = 2;
(this is your version number)onCreate()
, create all tables (create table events
& create table users
)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
You could use CREATE TABLE IF NOT EXISTS TABLENAME ...
as your query, that wouldn't overwrite your existing table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With