Adding Preference Settings using Preference Fragment Compat

It is very much likely that one needs to add preferences to their app which span the entire application and therefore can be accessed anywhere in the app without storing anything in database or making global variables. For an instance, in Open Event Organizer App we added the preferences to store the privacy policy, cookie policy etc. The user can access these items in Settings Preference which in device settings. In this blog post we will see how to add preference settings to the app by storing the data in shared preferences.

Specifications

The benefit of storing the data in shared preference and not in local storage is that the access time for the data is drastically reduced and the data persists even when the app is closed. We will use this library which is built on top of official preference-v7 library.

Firstly, we will make a preference resource layout file and add the preference for privacy policy and cookie policy in the preference screen.

<PreferenceScreen xmlns:android=”http://schemas.android.com/apk/res/android”>

<Preference
android:key=”@string/privacy_policy_key”
android:title=”@string/privacy_policy” />

<Preference
android:key=”@string/cookie_policy_key”
android:title=”@string/cookie_policy” />

</PreferenceScreen>

Make a separate preference fragment class named LegalPreferenceFragment which extends PreferenceFragmentCompat. Then we will override onCreatePreferenceFix() method.

Inside this, we will create an instance of Preference Manager and set shared preference name for it and set the preference using the layout file. This enables us to use findPreference() method to retrieve the layout preferences by their key. After, retrieving the preference we will set onClick listener to launch activity with an intent to open browser for the url passed in data bundle.

@Override
public void onCreatePreferencesFix(@Nullable Bundle bundle, String rootKey) {
PreferenceManager manager = getPreferenceManager();
manager.setSharedPreferencesName(Constants.FOSS_PREFS);

setPreferencesFromResource(R.xml.legal_preferences, rootKey);

findPreference(getString(R.string.privacy_policy_key)).setOnPreferenceClickListener(preference -> {
BrowserUtils.launchUrl(getContext(), PRIVACY_POLICY_URL);
return true;
});
findPreference(getString(R.string.cookie_policy_key)).setOnPreferenceClickListener(preference -> {
BrowserUtils.launchUrl(getContext(), COOKIE_POLICY_URL);
return true;
});
}

References

  1. Preference Fragment Compat library by Takisoft https://github.com/Gericop/Android-Support-Preference-V7-Fix
  2. Android Preference Documentation https://developer.android.com/reference/android/preference/PreferenceGroup
Continue ReadingAdding Preference Settings using Preference Fragment Compat

Adding List Preference Settings using Preference Fragment Compat

In this blog post we will see how we can add a Preference List in Settings which will display a list of radio buttons in UI which user can choose from. In Open Event Orga App, the Organizer had a choice to switch between viewing Net Sales or Gross Sales in the App’s Dashboard. We decided to use a preference list to allow the user to select between using Net or Gross Sales.

The benefit of using Preference List and not any other storage media (like SQLite) to store the information is that, Preference List stores the information as key-value pair in SharedPreferences which makes it easy to store and extract small amount of data with strong consistency guarantees and using less time. Let’s move on to the implementation.

Implementation

Firstly add the dependency in build.gradle.

implementation “com.takisoft.fix:preference-v7:27.1.0.0”

In the preferences layout file, we will use checkboxes.

<PreferenceScreen xmlns:android=”http://schemas.android.com/apk/res/android”>

<CheckBoxPreference
android:key=”@string/gross_sales_key”
android:title=”@string/gross_sales”
android:defaultValue=”true” />

<CheckBoxPreference
android:key=”@string/net_sales_key”
android:title=”@string/net_sales”
android:defaultValue=”false” />
</PreferenceScreen>

We will create SalesDataSettings class which extends PreferenceFragmentCompat and override onCreatePreferenceFix method. We will request PreferenceManager and set SharedPreferencesName. The manager will be used to store and retrieve key-value pairs from SharedPreferences. Using setPreferencesFromResource we will attach the layout file to the fragment.

PreferenceManager manager = getPreferenceManager();
manager.setSharedPreferencesName(Constants.FOSS_PREFS);

setPreferencesFromResource(R.xml.sales_data_display, rootKey);

We are using CheckBox Preferences and modifying their behaviour to work as a Radio Preference List because Radio reference is not provided by Android. We are initializing two checkboxes and attaching a preference listener to unset all other checkboxes which one is selected.

CheckBoxPreference netSales = (CheckBoxPreference) findPreference(NET_SALES);
CheckBoxPreference grossSales = (CheckBoxPreference) findPreference(GROSS_SALES);

Preference.OnPreferenceChangeListener listener = (preference, newValue) -> {
String key = preference.getKey();

switch (key) {
case GROSS_SALES:
netSales.setChecked(false);
break;
case NET_SALES:
grossSales.setChecked(false);
break;
default:
break;
}
return (Boolean) newValue;
};

netSales.setOnPreferenceChangeListener(listener);
grossSales.setOnPreferenceChangeListener(listener);

We can load SalesDataDisplay Fragment class when a preference button is clicked using fragment transactions as shown below.

findPreference(getString(R.string.sales_data_display_key)).setOnPreferenceClickListener(preference -> {
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, SalesDataSettings.newInstance())
.addToBackStack(null)
.commit();
return true;
});

References

  1. Shared Preferences Documentation https://developer.android.com/reference/android/content/SharedPreferences
  2. Gericop Takisoft Android-Support-Preference-V7-Fix https://github.com/Gericop/Android-Support-Preference-V7-Fix
  3. Codebase for Open Event Organizer App https://github.com/fossasia/open-event-orga-app
Continue ReadingAdding List Preference Settings using Preference Fragment Compat

Adding Events’ Payment Preferences to Eventyay Organizer Android App

The Open Event Organizer Android App allows creating events from the app itself. But organizers had to enter the payment information every time. To solve this problem, the PR#1058 was opened which saves the Organizers’ payment preferences in Event Settings.

The Open Event project offers 5 types of payment options:

Online:
1. Paypal
2. Stripe

Offline:
3. Cash payment
4. Bank Transfer
5. Cheques

Each of the above need the payment specific details to be saved. And stuffing all of them into a single Event Settings screen isn’t a good option. Therefore the following navigation was desired:

Event Settings -> Payment Preferences -> All options with their preferences

Android Developer guide references a simple method to achieve the above, which is by using nested preference screens. But unfortunately, there’s a bug in the support library and it cannot be implemented with  PreferenceFragmentCompat

So we had to apply a hack to the UI. We set an OnPreferenceClickListener as follows:

public class EventSettingsFragment extends PreferenceFragmentCompat {
   …
   @Override
   public void onCreatePreferencesFix(@Nullable Bundle bundle, String rootKey) {
       …

       findPreference(“payment_preferences”).setOnPreferenceClickListener(preference -> {
           FragmentTransaction transaction = getFragmentManager().beginTransaction();
           transaction
               .replace(R.id.fragment_container, PaymentPrefsFragment.newInstance())
               .addToBackStack(null)
               .commit();
           return true;
       });
   }
   …
}

Once the preference item “Payment Preferences” is clicked, we initiate a fragment transaction opening the Payment Preferences screen, and add it to the fragment back stack.

For each payment option, we have two things to consider:

  1. Is that payment option supported by the organizer?
  2. If yes, we need to store the necessary details in order to direct the payment to the organizer.

We are also keeping track of whether the organizer wants to keep using the same payment preferences for future events as well. This way we save the organizer’s effort of entering payment details for each new event.

<?xml version=“1.0” encoding=“utf-8”?>
<PreferenceScreen xmlns:android=“http://schemas.android.com/apk/res/android”>

   <CheckBoxPreference
       android:key=“use_payment_prefs”
       android:title=“@string/use_payment_prefs”
       android:summaryOn=“@string/using_payment_preferences”
       android:summaryOff=“@string/not_using_payment_preferences”
       android:defaultValue=“false” />

   <PreferenceCategory
       android:title=“Bank Transfer”>
       <CheckBoxPreference
           android:key=“accept_bank_transfers”
           android:title=“@string/accept_payment_by_bank_transfer”
           android:defaultValue=“false”/>

       <EditTextPreference
           android:key=“bank_details”
           android:title=“@string/bank_details” />
   </PreferenceCategory>
   …

</PreferenceScreen>

Now the only thing remaining is to set payment preferences once the Event Creation form is opened. Hence the following method is called in  CreateEventPresenter  sets the payment details for each option that the organizer has already saved the information for. It does this by using constants named like PREF… all declared in the  Constants.java  file.

using a custom Preference class which abstracts away some boilerplate code for us.

   public void setPaymentPreferences(Preferences preferences) {

       if (preferences.getBoolean(PREF_USE_PAYMENT_PREFS, false)) {
           
           event.setCanPayByBank(
               preferences.getBoolean(PREF_ACCEPT_BANK_TRANSFER, false)
           );
           event.setBankDetails(
               preferences.getString(PREF_BANK_DETAILS, null)
           );
           …
           getView().setPaymentBinding(event);
       }
   }

This is how the result looks like:

Resources

Continue ReadingAdding Events’ Payment Preferences to Eventyay Organizer Android App