Password protected setting in Android

Danielle H
2 min readJan 11, 2022

Or How to get user input before showing a setting dialog in Android

Some settings are more important than others. Adding a password to a specific setting is a way to make sure that the person changing this setting knows what they are doing. Another method is to show an Alert Dialog asking “Do you know what you’re doing?”. In both cases, we want to show the user a dialog and allow the user to change the setting only after they have answered accordingly.

So… Let’s do it!

We’ll start by taking a closer look at PreferenceFragmentCompat class, which is created automatically when you create a settings activity.

On first glance, it looks like OnPreferenceTreeClick is what we want. It fires when any preference in the fragment is clicked (each fragment can have multiple preferences), and returns a Boolean if the click was handled. So, we would check if it’s the setting we wish to protect, add an alert dialog, and return true if we don’t want to allow the user to change the preference, and false otherwise. Simple, right?

Wrong.

As is explained here, the return value doesn’t affect if the setting is shown or not. No matter what the function returns, the preference dialog is shown. So we need another solution.

The better solution in this case is the OnDisplayPreferencesDialog function, that is called before displaying the preference dialog. In order to continue and display the preference dialog, you need to call super.onDisplayPreferenceDialog().

So we can check if this setting is the setting we want to protect, create a dialog to get the password, check the password, and show the preference dialog only if password is correct ( see notes below!) or show an “Are you sure” dialog:

And this is what it looks like:

Success!

Hurray!

The code can be found in Gitlab:

Let me know if this solved a problem for you :)

IMPORTANT: This kind of password is NOT secure. I use it in cases where I just want to make sure the person changing this setting is someone who should be changing it. Don’t use this method to hide sensitive data!

IMPORTANT 2: You can use the same method to create an “Are you sure” alert.

--

--

Danielle H

I started programming in LabVIEW and Matlab, and quickly expanded to include Android, Swift, Flutter, Web(PHP, HTML, Javascript), Arduino and Processing.