How do I delete SharedPreferences data for my application?
I\'m creating an application that uses a lot of web services to sync data. For testing purposes, I need to
To remove specific values: SharedPreferences.Editor.remove() followed by a commit()
To remove them all SharedPreferences.Editor.clear()
followed by a commit()
If you don't care about the return value and you're using this from your application's main thread, consider using apply()
instead.
Removing all preferences:
SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().clear().commit();
Removing single preference:
SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().remove("KeyName").commit();
The Kotlin ktx way to clear all preferences:
val prefs: SharedPreferences = getSharedPreferences("prefsName", Context.MODE_PRIVATE)
prefs.edit(commit = true) {
clear()
}
Click here for all Shared preferences operations with examples
Deleting Android Shared Preferences in one line :-)
context.getSharedPreferences("YOUR_PREFS", 0).edit().clear().commit();
Or apply
for non-blocking asynchronous operation:
this.getSharedPreferences("YOUR_PREFS", 0).edit().clear().apply();
If it is for your testing. You can use adb commands.
adb shell pm clear <package name>
You can use the adb shell to do this even without a rooted phone. The only catch is that the app must be debuggable.
run-as <your package name> <command>
For example:
run-as com.asdf.blah rm /data/data/com.asdf.blah/databases/myDB.db
Alternatively, you can just do the above but without the command which will direct you to the app package root and allow you to execute more commands in the app's context.