I'm maintaining a long living app on Android, and I've decided to change the data model behind it merging a few SQLite databases into a single new one.
The thing is, if I just create the new DB and stop using the old ones, every app user out there will still have the old SQLite files in their local storage.
Is there a way to force a "clear data" upon a new version of the app? (I'm looking for the "right" way to do it, I know I can check if the new DB exists and act according, but I think there may be a better way)
Thanks
Whenever a database needs to be upgraded(when a user downloads a new version of an app, for example), the change in the database version number calls the onUpgrade() method, you can override thiis method provided with SQLiteOpenHelper class:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion
+" to "+newVersion
+", which will destroy all old data");
for (String string : table_names)
db.execSQL("drop table if exists "+ string);
onCreate(db);
}
Yes, you can define a BroadcastReceiver for the MY_PACKAGE_REPLACED action. In this receiver's onReceive method you can delete the databases. (API12+)
<receiver
android:name=".OnUpgradeReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
and the BroadcastReceiver
public class OnUpgradeReceiver extends BroadcastReceiver {
public OnUpgradeReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
context.deleteDatabase("YOUR_DATABASE_NAME");
}
}
notes that this will only trigger in case of updating (increasing the version code in Gradle file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With