North Border Software




Home Tutorials Hints & Tips About
Share on Facebook Share on Twitter

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")) {
      radioGroupColor.check(R.id.rbWhite);
   } else if (colorText.equals("slate")) {
      radioGroupColor.check(R.id.rbSlate);
   } else {
      radioGroupColor.check(R.id.rbGreen);
   }
}

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

prefs.edit().clear().commit();

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


Download Download tutorial set 2



© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo

Android Apps and Training