1

I have an app with a database version = 1. Now I want to upgrade my database to version = 2.

However my problem is when I am running updated application on previous version with changed database version it is calling onCreate() method instead of onUpgrade().

I know onCreate() is called when database is created for first time and onUpgrade() is called when we change the database version.

I went through a lot of stack overflow questions but couldn't able to get a solution

Note : I have a preloaded database created using SqliteManager stored in asset folder. What I have done till now is as below

Database :

private static String DB_PATH = "/data/data/context.getPackageName()/databases/";
private static String DB_NAME = "db_name";
private static final int DATABASE_VERSION = 2;

// reference of database
private SQLiteDatabase mySqliteDb;
private Context context;

public DBController(Context context) {

    super(context, DB_NAME, null, DATABASE_VERSION);
    this.context = context;
}

/****************** onCreate() ***********************/
@Override
public void onCreate(SQLiteDatabase database) {
    Log.v("On create method", "On create method");   // This log is printing
}

/********************* Upgrade ************************/
@Override
public void onUpgrade(SQLiteDatabase database, int version_old,
        int current_version) {

    Log.v("On upgrade method", version_old +"");

}

/************* Create Database *********************/
public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();

    if (dbExist) {
        Log.v("DATABASE call ", "DATABASE exists");   // This log is printing
        this.getWritableDatabase();

    } else {
        Log.v("DATABASE call ", "DATABASE not exist");
        this.getWritableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {
            // Log.e("Error", e.toString());
            throw new Error("Error copying database");
        }
    }

}

/***************** Check whether database exist or not *******************/
private boolean checkDataBase() {

    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    // Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DB_NAME);

    // 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[5120];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

/************************************ database open *************************************/
public void openDataBase() throws SQLException {

    String myPath = DB_PATH + DB_NAME;
    mySqliteDb = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);

}

And I am calling my database on my first activity

DBController dbController = new DBController(Login.this); 
try {
    dbController.createDataBase();
} catch (IOException e) {
    e.printStackTrace();
}

And after running my code

Log.v("On create method", "On create method");
Log.v("DATABASE call ", "DATABASE exists");

this two logs are printing. So I am unable to upgrade my database as it is not going to onUpgrade() block. Please help me if I am missing something here.

I found a similar type of question with my problem in stack overflow. Here is the link.

Community
  • 1
  • 1
Kunu
  • 5,078
  • 6
  • 33
  • 61
  • Make absolutely certain the db version on your device is 1 (with code to make doubly sure) :D. – Daniel Wilson Nov 23 '14 at 18:20
  • @DanielWilson Yes I am sure, I tried same thing by changing it to the version 3 also – Kunu Nov 23 '14 at 18:25
  • Put a call to onCreate() inside onUpgrade() - maybe your onUpgrade() is being removed due to the fact that it's essentially empty. Probably not but worth a try. – Daniel Wilson Nov 23 '14 at 18:31
  • @DanielWilson My `onUpgrade()` is not empty actually. I am inserting some data there. I just didn't thought it is necessary to put those code here as Log inside `onUpgrade()` is also not printing :( – Kunu Nov 23 '14 at 18:35
  • Cool yeah thought so. This might be helpful to you: http://stackoverflow.com/questions/14332462/database-onupgrade-method-is-never-called?rq=1 I will add it as an answer because I believe it will help others – Daniel Wilson Nov 23 '14 at 18:38
  • Yeah there is a comment (by user BenjaminButton) here referencing the same problem http://stackoverflow.com/questions/7173896/onupgrade-database-oldversion-newversion?rq=1 – Daniel Wilson Nov 23 '14 at 18:48
  • When `onCreate` or `onUpdate` succeeds, the database is created with the correct version. However, `copyDataBase` then overwrites the file with something else. – CL. Nov 23 '14 at 21:28
  • @CL.So here what should I do ? Where should I call `copyDataBase` ? – Kunu Nov 24 '14 at 04:23
  • Consider using https://github.com/jgilfelt/android-sqlite-asset-helper instead. – laalto Nov 24 '14 at 05:46
  • @laalto Okay, Let me try it first, thank you. – Kunu Nov 24 '14 at 05:55
  • @laalto, Can you tell me what might be the problem here ? And I referred to your link also , however still I am stuck with same problem. – Kunu Nov 24 '14 at 10:23
  • The code is based on an ancient blog post from 2009 and it's broken in many ways. I've given up paying attention to SO questions with variants of that code a long time ago. – laalto Nov 24 '14 at 10:26
  • @laalto I tried to use `android-sqlite-asset-helper ` also . And I upgraded a column using code `ALTER TABLE TableName ADD COLUMN myColName TEXT;` in existing table. My code is in sql file `db_name_upgrade_1-2.sql` stored in assets folder. Is there anything I am doing wrong in during upgrade. But this time also it showing `No such column myColName` – Kunu Nov 24 '14 at 11:03

1 Answers1

0

It seems the database version is not correctly recorded unless you call getReadableDatabase or getWritableDatabase at some stage on creation of the db. According to user Vovkab, you should call either of these things in the constructor of your db to trigger the upgrade.

EDIT: I just wanted to add a couple things to this answer - most notably, this answer is the best description of upgrading databases I have seen. Next up, it would seem the key difference between this code and all the other similar SO problems out there is the fact that your database resides in the assets folder. I think this question needs a combination of onUpgrade outlined in the previous link, and a CopyNewDatabaseFromAsset() call outlined by sandeep_jagtap here.

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
          CopyNewDatabaseFromAsset();
    } 
Community
  • 1
  • 1
Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135
  • But I am calling `this.getWritableDatabase();` in my createDatabase method. And it also showing that database is exist still it is executing `onCreate()` block – Kunu Nov 23 '14 at 18:58
  • Did you try and place the line in the constructor? Before the call to super – Daniel Wilson Nov 24 '14 at 09:38
  • It showing `Implicit super constructor SQLiteOpenHelper() is undefined. Must explicitly invoke another constructor` error in that case. – Kunu Nov 24 '14 at 09:44