I have an app on the Google Play market. For various reasons that I won't bother going into, I have changed the type of some of my preferences. For example a preference type was an Integer and in the most recent version it is now a String. I imagine this isn't good practice but unfortunately I had to do it.
My concern is that when someone updates to the new version their app will crash as the preference types have changed. For this reason I would like to clear the preferences whenever the app is updated (again I realise not ideal!)
Is this possible?
You use remove() to remove specific preferences, you use clear() to remove them all.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory.
Preferences in Android are used to keep track of application and user preferences. In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context)
The SharedPreferences.Editor
class has a clear()
function, what removes all your stored preferences (after a commit()
). You could create a boolean flag which will indicate if updated needed:
void updatePreferences() {
SharedPreferences prefs = ...;
if(prefs.getBoolean("update_required", true)) {
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
/*....make the updates....*/
editor.putBoolean("update_required", false)
editor.commit();
}
}
And after that you need to call this in your main (first starting) activity, before you access any preferences.
EDIT:
To get the current version (The versionCode declared in the manifest):
int version = 1;
try {
version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if(version > ...) {
//do something
}
EDIT
If you want to do some updating operation, whenever the version changes, then you can do something like this:
void runUpdatesIfNecessary() {
int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
SharedPreferences prefs = ...;
if (prefs.getInt("lastUpdate", 0) != versionCode) {
try {
runUpdates();
// Commiting in the preferences, that the update was successful.
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("lastUpdate", versionCode);
editor.commit();
} catch(Throwable t) {
// update failed, or cancelled
}
}
}
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