Implementing Country Preference in Orga App

In the Open Event Orga App, there was no option earlier to save the country preference in the shared preference. So every time the user had to select the country while creating events. Hence an option to select a country was added to the Event Settings. So any value which gets selected here acts as a default country while creation of events.


  • Add the constant key to the class.
public static final String PREF_PAYMENT_COUNTRY = “key”;
  • Create a class which extends DialogPreference. It is in this class that all the code related to the dialog which appears in selecting the Country preference will appear. First we create a layout for the dialog box. Following is the XML file for the same.
<?xml version=“1.0” encoding=“utf-8”?>

<LinearLayout xmlns:android=“”

      android:layout_marginTop=“@dimen/spacing_small” />

  • Now we create the CountryPreference constructor where we specify the UI Of the dialog box. It would include the positive and negative button.
private int layoutResourceId = R.layout.dialog_payment_country;
private int savedIndex;

public CountryPreference(Context context, AttributeSet attrs) {
  super(context, attrs, R.attr.preferenceStyle);
  • We override the method onSetInitialValue where we set the preference of the country in the shared preference. We call the method setCountry and pass the persisted value.
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
  setCountry(restorePersistedValue ? getPersistedInt(savedIndex) : (int) defaultValue);
  super.onSetInitialValue(restorePersistedValue, defaultValue);


public void setCountry(int index) {
  savedIndex = index;
  • We create a class CountryPreferenceCompat which extends PreferenceDialogFragmentCompat. It is here that we initialize the spinner and set the adapter. It is here that we override the method onDialogClosed which should happen when the dialog box is closed. Following is the code for the same.
public void onDialogClosed(boolean positiveResult) {
  if (positiveResult) {
      DialogPreference preference = getPreference();
      if (preference instanceof CountryPreference) {
          CountryPreference countryPreference = ((CountryPreference) preference);
  • In the PaymentPrefsFragment the code for initialization of the dialog is added. We override the onDisplayPreferenceDialog.
public void onDisplayPreferenceDialog(Preference preference) {
  CountryPreferenceFragmentCompat dialogFragment = null;
  if (preference instanceof CountryPreference)
      dialogFragment = CountryPreferenceFragmentCompat.newInstance(Constants.PREF_PAYMENT_COUNTRY);

  if (dialogFragment != null) {
      dialogFragment.setTargetFragment(this, 1);,
          “” +
  } else {
  • Now the PaymentCountry spinner can be seen on testing.


  1. Building Custom Preference
  2. StackOverflow solution  


Continue ReadingImplementing Country Preference in Orga App