Android, Development, Kotlin, Test

Clear all Android SharedPreferences

It may happen you would need to clear your all of your SharedPreferences without knowing in advance their keys.


This can happen when you are writing tests: you don’t want your production code to publicly expose your SharedPreferences keys neither you need a clear() method, so you didn’t implement it. You may also need to clear third party SharedPreferences to which you don’t have direct access.

Without changing your production code there is something you can do:

  • access the app SharedPreferences folder
  • get the SharedPreferences editor for each file
  • clear the SharedPreferences

You can use the following code, called in a @BeforeEach annotated method, to be sure each of your tests will run in a clean environment.

private fun clearAllSharedPreferences(context: Context) {
    val sharedPreferencesPath = File(context.filesDir.parentFile!!.absolutePath + File.separator + "shared_prefs")
    sharedPreferencesPath.listFiles()?.forEach { file ->
        context.getSharedPreferences(file.nameWithoutExtension, Context.MODE_PRIVATE).edit { clear() }


  • Be sure to include androidx.core:core-ktx in your project to have that edit() method
  • If you are running your tests using Espresso you can access the app Context using InstrumentationRegistry.getInstrumentation().targetContext

Happy coding!

Android, Development, Java, Kotlin

How to debug an Annotation Processor in Android Studio

Writing an Annotation Processor in Java/Kotlin is a very interesting task and debugging comes very handy, but unfortunately it seems not so easy to start a debug session.

rubber ducks

The following information are valid for Android Studio 3.6.3 and Kotlin 1.3.71. Gradle is the build tool used for the project.

First thing to do is setup a new Run/Debug Configuration in Android Studio:

  • Choose Run from the main menu
  • Choose Edit Configurations
  • Now click on the + symbol in the top left corner to add a new Configuration
  • Choose Remote from the list
  • Give it a friendly name (e.g. AnnotationProcessorDebugger)

Setup your breakpoints wherever you need them and then run this command from the terminal:

./gradlew --no-daemon -Dorg.gradle.debug=true :APP_MODULE_NAME:clean :APP_MODULE_NAME:compileDebugJavaWithJavac

Replace APP_MODULE_NAME with the name of the module having annotations which you want to debug. You will see the process will start and suddenly stop on > Starting Daemon waiting for you to do something.

Now, click on the Debug icon in the Toolbar (having selected the previously created AnnotationProcessorDebugger configuration) and the debugger will hit your breakpoints!

Additional info:

The clean task seems to be necessary.

Unfortunately, sometimes these steps are not enough, or simply don’t work, the debugger won’t hit your breakpoints. I see somebody else solved the issue after adding the following line to their file.