moji
moji

Reputation: 63

How can Upgrade sqlite database to next version with saving user data

i have an application with version 1.0 and now i hade made newxt version and now i want ot upgrade the database but i can not upgrade the database. the android studio give error from this line:

 db = this.getReadableDatabase();

. here is full code:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db = this.getReadableDatabase();
    Cursor SignalRes = db.rawQuery("select * from signal", null);

    db.execSQL("DROP TABLE IF EXISTS signal");
    onCreate(db);

    SignalRes.moveToFirst();
    while (!SignalRes.isAfterLast()) {
        insertSignal((SignalRes.getInt(0)), SignalRes.getString(1), SignalRes.getString(2)
                , SignalRes.getString(3), SignalRes.getString(4), SignalRes.getString(5)
                , SignalRes.getString(6), SignalRes.getString(7), SignalRes.getString(8));
        SignalRes.moveToNext();
    }
    SignalRes.close();

Upvotes: 0

Views: 63

Answers (2)

Charles Li
Charles Li

Reputation: 1925

onUpgrade already has a db variable passed in, so you should just use that variable rather than assigning to it again. It will be better if you can post the error message as well, but I'm suspecting you are opening the database recursively.

By the way, check this post out, you also need to clarify the relation between newVersion and oldVersion to indicate when you want the database to be updated.

So your code should look something like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < YOUR_NEW_DB_VERSION) {
         db.execSQL(YOUR_QUERY_TO_MOVE_DATA_FROM_TABLE1_TO_TABLE2);
         db.execSQL(YOUR_QUERY_TO_DROP_TABLE1);
    }
}

Upvotes: 2

Hayrullah Cansu
Hayrullah Cansu

Reputation: 262

1) Define a variable like that private static final int DATABASE_VERSION = 5;

2) Your SQLiteOpenHelper Class Constructor and super method will check version

public EzberletDB(Context context) {
    super(context, DATABASE_NAME,null,DATABASE_VERSION);
    this.context=context;
    SQLiteDatabase db = getWritableDatabase();
    db.close();
    try {
        context.openOrCreateDatabase(DATABASE_NAME, context.MODE_PRIVATE, null); 
    } catch (Exception e) {

        context.openOrCreateDatabase(DATABASE_NAME,context.MODE_PRIVATE,null);
    }
}

3) onUpgrade method if version chanced that method will execute

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    try {
        String query="";
        query = "DROP TABLE IF EXISTS signal";
        db.execSQL(query);
        onCreate(db);
    } catch (SQLException e) {
        e.printStackTrace();
        Message.message(context,""+e);
    }
}

Finally: if you increase DATABASE_VERSION to 6, your db will be updated. I hope you can't lose user datas with this way.

Upvotes: -1

Related Questions