Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Data on update

Tags:

android

sqlite

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

like image 505
Cheborra Avatar asked Jan 25 '26 03:01

Cheborra


2 Answers

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);
}
like image 90
Daniel Conde Marin Avatar answered Jan 26 '26 16:01

Daniel Conde Marin


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)

like image 31
zaPlayer Avatar answered Jan 26 '26 18:01

zaPlayer