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:
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:
Happy coding!