Search code examples
javaandroidandroid-sqlitesqliteopenhelper

SQLiteOpenHelper : OnCreate Function not called


OnCreate() not called even after calling getWritableDatabase() in the constructor

package com.example.user.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DB_Test dbTest = new DB_Test(getApplicationContext());
    }
}

Tried calling getWritableDatabase() in the constructor but, not working

package com.example.user.myapplication;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by user on 11-Mar-16.
 */
public class DB_Test extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "productDB.db";
    public DB_Test(Context context) {
        super(context, DATABASE_NAME, null,DATABASE_VERSION);
        Log.v("MainActivity", "Constructor Working");
        getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.v("MainActivity","onCreate Working");
        String CREATE_PRODUCTS_TABLE = "CREATE TABLE products(column_id INTEGER PRIMARY KEY,column_product_name TEXT,column_quantity INTEGER)";
        db.execSQL(CREATE_PRODUCTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.v("MainActivity", "OnUpgrade Working");
        db.execSQL("DROP TABLE IF EXISTS products");
        onCreate(db);
    }
}

Solution

  • If your database has been created it is not called. If you change the version number then onUpdate will be called.