soren.qvist
soren.qvist

Reputation: 7416

Extended SQLiteOpenHelper class calls onCreate every time?

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "test.db";
    private static final int DB_VERSION = 1;
    private boolean DB_JUST_CREATED = false;

    private Context _context;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        _context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("WOD", "onCreate firing");
        DB_JUST_CREATED = true;
    }

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

    }

    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        SQLiteDatabase db = super.getWritableDatabase();

        // Copy db from assets folder if db was just created.
        if(DB_JUST_CREATED == true) {
            Log.d("WOD", "Creating db");
            try {
                // Open InputStream to assets db.
                InputStream inStream = _context.getAssets().open(DB_NAME);

                // Open OutputStream to new db.
                OutputStream outStream = new FileOutputStream(db.getPath());

                //transfer bytes from the input-file to the output-file
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inStream.read(buffer)) > 0)
                {
                    outStream.write(buffer, 0, length);
                }

                //Close the streams
                outStream.flush();
                outStream.close();
                inStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return db;
    }

}

I've tried creating a DatabaseHelper object in several different activities and it's the same thing everytime, onCreate() is fired and then it creates a new database. I checked the DDMS file explorer and sure enough, the database stays there after it's created, even if i force stop the application, so onCreate shouldn't even be called. What's going on here?

Upvotes: 1

Views: 1809

Answers (2)

Jeff Gilfelt
Jeff Gilfelt

Reputation: 26159

You shouldn't really be overriding getWritableDatabase and calling the superclass method in that way.

Take a look at what that method does under the covers here: http://codesearch.google.com/codesearch#uX1GffpyOZk/core/java/android/database/sqlite/SQLiteOpenHelper.java&q=package:android.git.kernel.org%20file:android/database/sqlite/SQLiteOpenHelper.java&l=1

You will need to ensure the SQLite database user-version is set to the current version after you copy the file from assets to ensure that onCreate is not called upon subsequent calls to your getWritableDatabase implementation:

db = _context.openOrCreateDatabase(DB_NAME, 0, null);
db.setVersion(DB_VERSION);

Upvotes: 2

Its not blank
Its not blank

Reputation: 3095

try these it works for me

     /**
   * Creates a empty database on the system and rewrites it with your own
   * database.
   * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        Log.v("DB", "No DB");
        // database does't exist yet.

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getResources().openRawResource(
            R.raw.diary_database);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

Upvotes: 3

Related Questions