Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the database doesn't work -Android

I wrote some code to ensure that my database will be updated properly when I will release updates to my application.

The problem is that the OnUpdate() function of the SQLiteOpenHelper is never called. Here is the code I wrote in the main activity -

    SharedPreferences DB_ver = getSharedPreferences(PREFS_NAME, 0);
    myDbHelper = new DataBaseHelper(con, DB_ver.getInt("DB_ver", 1));
    try {
        if(DB_ver.getInt("DB_ver", 1) !=getPackageManager().getPackageInfo(getPackageName(), 0).versionCode )
        {
              SharedPreferences.Editor editor = DB_ver.edit();
              editor.putInt("DB_ver", getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

Here is the constructor of SQLiteOpenHelper(which extends SQLiteOpenHelper) -

public DataBaseHelper(Context context,int ver_code) {       
    super(context, DB_NAME, null, ver_code);
    this.myContext = context;
}   

Now I understood that the Super line is supposed to call the onUpgrade() function automatically, but it doesn't.

I've tested the function onUpgrade() separately, and it works.

Does anyone know what's the problem?

Thanks!

like image 211
Tofira Avatar asked Feb 03 '26 20:02

Tofira


1 Answers

What your doing is really not neccessary. SQLiteOpenHelper does everything you need. Here's a possible scenario. SQLiteOpenHelper has a getVersion() method in case you need to query it at one point (I never did):

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

  private static final String dbname = "whatever";
  private static final int    dbversion = 1;  // your first version
//private static final int    dbversion = 2;  // your second version
//private static final int    dbversion = 3;  // your third version

  public MySQLiteOpenHelper(Context context) {
    super(context, dbname, null, dbversion);
    this.context = context;
  }

  @Override
  public void onCreate(SQLiteDatabase sqliteDatabase) {
    // ... Create first database content
  }

  @Override
  public void onUpgrade(SQLiteDatabase sqliteDatabase, int oldVersion, int newVersion) {
    switch (newVersion) {
      case dbversion:  // suppose your on third version
        if (oldVersion == 1) {
          upgradeFrom1To2(sqliteDatabase);
          upgradeFrom2To3(sqliteDatabase);
        }

        if (oldVersion == 2) {
          upgradeFrom2To3(sqliteDatabase);
        }

        break;
      default:
        break;
    }
  }

  public void upgradeFrom1To2(SQLiteDatabase sqliteDatabase) {
    // ...
  }

  public void upgradeFrom2To3(SQLiteDatabase sqliteDatabase) {
    // ...
  }
}
like image 101
Harald Wilhelm Avatar answered Feb 06 '26 11:02

Harald Wilhelm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!