Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing App Data on update

I need to clear(equivalent to Clear Data in App Settings) all the old data in the app programmatically when the user updates the app from Google Play Store or any other sources. This is because I don't need any of the existing data from the old app since I have changed everything in the new app compared to the old one.

I thought of implementing a version check at the app startup, but I can't find a way to get the app's previous versionCode or versionName. The only way I figured out to clear the data is to check the lastUpdateTime at the time of publishing the app. But it's not reliable since the user has other ways or sources of getting the app (like sharing it with a friend or if the user had a backup of the old app).

Any Suggestions?

like image 430
Joshua Avatar asked Jan 30 '18 11:01

Joshua


2 Answers

You can store versionCode in SharedPreferences and compare with current versionCode

For clear all data you just need to clear all value of SharedPreferences, Local Database and all local files which you have store.

public void clearData()
    {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int mCurrentVersion = pInfo.versionCode;
            SharedPreferences mSharedPreferences = getSharedPreferences("app_name",  Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mSharedPreferences.edit();
            mEditor.apply();
            int last_version = mSharedPreferences.getInt("last_version", -1);
            if(last_version != mCurrentVersion)
            {
                //clear all your data like database, share preference, local file 
                //Note : Don't delete last_version value in share preference
            }
            mEditor.putInt("last_version", mCurrentVersion);
            mEditor.commit();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

Note : Don't delete last_version value in share preference.

like image 191
Niranj Patel Avatar answered Nov 12 '22 02:11

Niranj Patel


You can simply use a PACKAGE_REPLACED receiver which gets fired whenever a package is replaced in your phone (also happens when updating an app). Declare it in your manifest:

<receiver android:name=".UpdateReciever">
    <intent-filter>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
        <data android:scheme="package" android:path="com.my.app" />
    </intent-filter>
</receiver>

And add your receiver class. onReceive will get called when the app is updated:

public class UpdateReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context con, Intent intent) {

    }
}

EDIT: you don't need to filter the package. Use MY_PACKAGE_REPLACED instead which will fire only for your app.

like image 26
Drilon Blakqori Avatar answered Nov 12 '22 03:11

Drilon Blakqori