abhig10
abhig10

Reputation: 555

onCreate method doesn't get called in DatabaseHandler extends SQLiteOpenHelper

This is basically my first android app and I have been trying to use a prefilled sqllite database to work out my requirements.

My problem is that onCreate function does not gets called.

I have taken bits of codes from many places and combined them to form this class.

Updating prepopulated database in Android

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

And some others from android.com

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.Random;

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

public class DatabaseHandler extends SQLiteOpenHelper {

    SQLiteDatabase db;
    private static final String TAG = "DataBaseHelper";
    int id = 0;
    Random random = new Random();
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    // Constructor
    public DatabaseHandler(Context context) {
        super(context, DefinitionContract.DATABASE_NAME, null, DefinitionContract.DATABASE_VERSION);
        Log.d(TAG, "DatabaseHandler constructor called\n");
        db = getWritableDatabase();
        this.myContext = context;
        //createDB();
    }

    @Override
    public void onCreate(SQLiteDatabase db){
        Log.d(TAG, "onCreate called\n");
        createDB();
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "onUpgrade called\n");
        Log.w(TAG, "Upgrading DB from version " + oldVersion + " to " +
                    newVersion + ", which will destroy all old data");

        // Drop older table if existed
        String sql  = "DROP TABLE IF EXISTS " + DefinitionContract.CATEGORY_TABLE_NAME;
        db.execSQL(sql);

        sql = "DROP TABLE IF EXISTS " + DefinitionContract.CONTENTS_TABLE_NAME;
        db.execSQL(sql);

        // Create table again
        onCreate(db);
    }

    public void createDataBase(SQLiteDatabase db) {
        Log.d(TAG, "createDataBase called\n");
        createDB();
        db.execSQL(DefinitionContract.CREATE_CATEGORY_TABLE);
        db.execSQL(DefinitionContract.CREATE_CONTENTS_TABLE);
    }

    private void createDB() {
        Log.d(TAG, "createDB called\n");
        boolean dbExist = dbExists();
        Log.d("SQL Helper", "Condition:\n");
        if(!dbExist) {
            Log.d("SQL Helper", "Condition 1\n");
            copyDataBase();
        } else if(dbExist) {
            Log.d("SQL Helper", "Condition 2\n");
            copyDataBase();
        }
    }

    private boolean dbExists() {
        Log.d(TAG, "dbExists called\n");
        //File dbFile = new File(DefinitionContract.DATABASE_PATH + DefinitionContract.DATABASE_NAME);
        //return dbFile.exists();

        SQLiteDatabase db = null;
        try {
            String dbPath = DefinitionContract.DATABASE_PATH + DefinitionContract.DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(DefinitionContract.DATABASE_VERSION);
        }
        catch(SQLiteException e){
            Log.e("SQL Helper", "database not found");
        }
        if(db != null) {
            db.close();
        }
        return db != null ? true : false;
    }

    private void copyDataBase() {
        Log.d(TAG, "copyDataBase called \n");
        InputStream iStream = null;
        OutputStream oStream = null;
        String outFilePath = DefinitionContract.DATABASE_PATH + DefinitionContract.DATABASE_NAME;
        try{
            iStream = myContext.getAssets().open(DefinitionContract.DATABASE_NAME_EXT);
            oStream = new FileOutputStream(outFilePath);
            byte[] buffer = new byte[1024];
            int length;
            while((length = iStream.read(buffer))>0) {
                oStream.write(buffer,0,length);
            }
            oStream.flush();
            oStream.close();
            iStream.close();
        }
        catch(IOException ioe){
            throw new Error("Problem copying database from resource file.");
        }
    }

    public void openDataBase() throws SQLException {
        String myPath = DefinitionContract.DATABASE_PATH + DefinitionContract.DATABASE_NAME_EXT;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        Log.d(TAG, "close called\n");
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    public void readDB() {
        Log.d(TAG, "readDB called\n");
        String selectQuery = "SELECT  * FROM " + DefinitionContract.DATABASE_ONLYNAME+"."+DefinitionContract.CATEGORY_TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                int arraySize = cursor.getColumnCount();
                String newlog   = "arraySize=" + arraySize + "*****";
                for(int i = 0; i < arraySize; i++) {
                    newlog  = newlog + cursor.getString(i)+ "\n";
                }

                Log.d("Details: ", newlog);
            } while (cursor.moveToNext());
        }
    }

}

I have already done a google search and tried to fix it but it doesn't work yet.

Android SQLiteOpenHelper : onCreate() method is not called. Why?

SQLiteOpenHelper failing to call onCreate?

LogCat showns only "DataBaseHandler constructor called" and then "shutting down VM" after that

But if I remove the db = getWritableDatabase(); line from my constructor it works further and shows that the readDB() function is being called.

Some definitions that might help in understanding my code:

public static final String DATABASE_NAME        = "mydb.db";

public static final String DATABASE_NAME_EXT        = "mydb.sqllite";

// Database path
public static final String DATABASE_PATH = "/data/data/com.abhishekgdotcom.collection/databases/";

Any help guys?

Upvotes: 0

Views: 2244

Answers (2)

abhig10
abhig10

Reputation: 555

Well, the real reason why onCreate() method wasn't working for me because it is called only the first time the app runs. Or when you change the DATABASE_VERSION then onUpgrade gets called which in turn calls the onCreate method again.

I believe this is the default android working.

P.S I could get the onCreate working everytime by either changing the database version or deleting the database file from /data/data/packagename/databases/

Upvotes: 1

thelawnmowerman
thelawnmowerman

Reputation: 12136

I would recommend you another organization of code, since you make many unrelated things in the same class. Usually a good design is to define a OpenHelper class that inherits from SQLiteHelper that just creates or updates the databasem nothing else. Then, from another external class (usually from your activity), instantiate that OpenHelper class and then call getWritableDatabase() from there. Maybe you will find the bug easily.

Upvotes: 0

Related Questions