Skip to content

Instantly share code, notes, and snippets.

@zmdominguez
Last active November 16, 2018 05:19
Show Gist options
  • Save zmdominguez/04a0fa053a00f45fe535d310656ec50e to your computer and use it in GitHub Desktop.
Save zmdominguez/04a0fa053a00f45fe535d310656ec50e to your computer and use it in GitHub Desktop.
Selectively reset Shared Preferences

This is a helper function for an app's debug or development drawer and is designed to be pasted into an Activity. It retrieves all files from shared_prefs and allows the user to choose which files to reset to default values. It is extremely helpful when testing one-shot scenarios such as for hints or onboarding, etc.

It assumes that the files are named in a consistent and predictable way -- more specifically by prefixing them with the application ID as mentioned here. For maximum consistency, this assumes that files are named similar to how the system names the default SharedPreferences file (MY.PACKAGE.ID_my_preferences).

All the application-specific preferences files are displayed in an AlertDialog. For readability, the application ID is stripped out.

fun resetPreferences() {
val dataDir = File("${filesDir.parent}/shared_prefs")
// Get the prefs files we are concerned with
val sharedPrefsFiles = dataDir.listFiles().filter { file ->
file.name.startsWith(BuildConfig.APPLICATION_ID)
}
// Get the nice displayable name
val sharedPrefsFileNames = sharedPrefsFiles.map {
it.name
.removeSuffix(".xml")
.removePrefix(BuildConfig.APPLICATION_ID)
.removePrefix("_")
}.toTypedArray()
val selectedItems = mutableListOf<Int>()
val alert = AlertDialog.Builder(this).apply {
setTitle("Reset Preferences")
setMultiChoiceItems(sharedPrefsFileNames, null
) { _, which, isChecked ->
when {
isChecked -> selectedItems.add(which)
selectedItems.contains(which) -> selectedItems.remove(which)
}
}
setPositiveButton("Clear", null)
setNegativeButton("Cancel", null)
}.create()
alert.setOnShowListener {
alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { _ ->
selectedItems.forEach { prefIndex ->
val prefName = sharedPrefsFiles[prefIndex].name.split(".xml").first()
getSharedPreferences(prefName, Context.MODE_PRIVATE).edit().clear().apply()
alert.dismiss()
}
}
}
alert.show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment