Home Tutorials Hints & Tips

Getting Started in Android Development

Part 31 - Clearing Shared Preferences

In this tutorial the shared preferences are tidied up and the clear data button completed. If you tested the example built in parts 29 and 30 you would notice that when you access the SettingsActivity the radio button always defaults to the "white" value irrespective of what the shared preference is set to.

Therefore, we are going the read the shared preferences when we enter the SettingsActivity in order to set the corresponding radio button. An object of shared preference is defined.

SharedPreferences getData;

Then the myPrefs file is accessed.

getData = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);

A private method called setRadioButton() is defined and called in the onCreate() method. Using nested if else statements the correct radio button is set with the code below:

private void setRadioButton() {
   String colorText = getData.getString("color_key", "white");
   if (colorText.equals("white")) {
   } else if (colorText.equals("slate")) {
   } else {

The process of clearing shared preferences is straightforward. Within the onClick() method for the clear data button, just one line of code is needed.


After this tutorial your SettingsActivity should look similar to the one below:

Download Download tutorial set 2

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved