HomeAbout MeContact Me

Clear all Android SharedPreferences

By Emanuele Papa
Published in Android
December 29, 2020
1 min read
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() }
    }
}

Notes:

  • 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!


Tags

#android#development#test
Previous Article
How to debug an Annotation Processor in Android Studio
Emanuele Papa

Emanuele Papa

Android Developer

Topics

Android
AWS
Development
Info
Linux
Modding
Smart Home
Windows

Related Posts

Enable the new Android Auto UI
August 25, 2019
1 min
Copyright © Emanuele Papa 2021, All Rights Reserved.

Quick Links

HomeAbout MeContact MeRSS Feed

Social Media