Example usage for android.preference ListPreference setValueIndex

List of usage examples for android.preference ListPreference setValueIndex

Introduction

In this page you can find the example usage for android.preference ListPreference setValueIndex.

Prototype

public void setValueIndex(int index) 

Source Link

Document

Sets the value to the given index from the entry values.

Usage

From source file:org.dmfs.webcal.fragments.PreferencesFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.webcal_preference);
    ListPreference locales = (ListPreference) findPreference("content_location");

    locales.setOnPreferenceChangeListener(PrefUpdater);

    try {/*from w  w w.  ja  va 2s.  c  o  m*/
        getCountries();

        locales.setEntries(mCountryNames);
        locales.setEntryValues(mCountryCodes);
    } catch (Exception e) {
        Log.e(TAG, "could not load country list", e);
    }

    int index = locales.findIndexOfValue(locales.getValue());
    if (index >= 0) {
        locales.setSummary(locales.getEntries()[index]);
    } else {
        locales.setSummary(locales.getEntries()[0]);
        locales.setValueIndex(0);
    }
}

From source file:com.ovrhere.android.currencyconverter.ui.fragments.SettingsFragment.java

/** Finds and sets the update summary. Additionally sets default
 * value based on interval /*from   w  w w. java  2s.  com*/
 * @param interval The interval to show 
 * @param updateList The preference to update the summary */
private void findAndSetUpdateSummary(final int interval, ListPreference updateList) {
    CharSequence[] labels = updateList.getEntries();
    CharSequence[] values = updateList.getEntryValues();

    if (labels.length != values.length) {
        Log.w(CLASS_NAME, "Labels and values mismatch!");
        //if there is a mismatch, we know nothing.
        return;
    }
    final int SIZE = labels.length;
    for (int index = 0; index < SIZE; index++) {
        if (values[index].equals(String.valueOf(interval))) {
            //same value, so label it as such.
            updateList.setSummary(labels[index]);
            updateList.setValueIndex(index);
            return;
        }
    }
}

From source file:nl.hnogames.domoticz.Preference.Preference.java

private void setStartUpScreenDefaultValue() {
    int defaultValue = mSharedPrefs.getStartupScreenIndex();
    ListPreference startup_screen = (ListPreference) findPreference("startup_screen");
    startup_screen.setValueIndex(defaultValue);
}

From source file:org.span.manager.ChangeSettingsActivity.java

private void updateView() {

    // user id//from www .ja  v a2 s. c om
    EditTextPreference uidEditTextPref = (EditTextPreference) findPreference("uidpref");
    uidEditTextPref.setText(manetcfg.getUserId());

    // wifi group
    wifiGroupPref = (PreferenceGroup) findPreference("wifiprefs");
    boolean bluetoothOn = manetcfg.isUsingBluetooth();
    wifiGroupPref.setEnabled(!bluetoothOn);

    // wifi encryption algorithm
    WifiEncryptionAlgorithmEnum encAlgorithm = manetcfg.getWifiEncryptionAlgorithm();
    ListPreference wifiEncAlgorithmPref = (ListPreference) findPreference("encalgorithmpref");
    wifiEncAlgorithmPref.setEnabled(false); // TODO: disable until tested
    wifiEncAlgorithmPref.setEntries(WifiEncryptionAlgorithmEnum.descriptionValues());
    wifiEncAlgorithmPref.setEntryValues(WifiEncryptionAlgorithmEnum.stringValues());
    wifiEncAlgorithmPref.setValueIndex(encAlgorithm.ordinal());

    // wifi encryption setup method
    ListPreference wifiEncSetupMethodPref = (ListPreference) findPreference("encsetuppref");
    wifiEncSetupMethodPref.setEnabled(false); // TODO: disable until tested
    if (encAlgorithm == WifiEncryptionAlgorithmEnum.NONE) {
        wifiEncSetupMethodPref.setEnabled(false);
    } else {
        wifiEncSetupMethodPref.setEnabled(true);
        if (manetcfg.getWifiDriver().startsWith("softap")
                || manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
            if (wifiEncSetupMethodPref != null) {
                wifiGroupPref.removePreference(wifiEncSetupMethodPref);
            }
        } else {
            wifiEncSetupMethodPref.setEntries(WifiEncryptionSetupMethodEnum.descriptionValues());
            wifiEncSetupMethodPref.setEntryValues(WifiEncryptionSetupMethodEnum.stringValues());
            wifiEncSetupMethodPref.setValueIndex(manetcfg.getWifiEncryptionSetupMethod().ordinal());
        }
    }

    // wifi encryption password
    final EditTextPreference wifiEncPasswordEditTextPref = (EditTextPreference) findPreference("passwordpref");
    wifiEncPasswordEditTextPref.setEnabled(false); // TODO: disable until tested
    if (encAlgorithm == WifiEncryptionAlgorithmEnum.NONE) {
        wifiEncPasswordEditTextPref.setEnabled(false);
    } else {
        wifiEncPasswordEditTextPref.setEnabled(true);
        final int origTextColorWifiEncKey = wifiEncPasswordEditTextPref.getEditText().getCurrentTextColor();
        if (manetcfg.getWifiDriver().startsWith("softap")
                || manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
            Validation.setupWpaEncryptionValidators(wifiEncPasswordEditTextPref, origTextColorWifiEncKey);
        } else {
            Validation.setupWepEncryptionValidators(wifiEncPasswordEditTextPref, origTextColorWifiEncKey);
        }
        wifiEncPasswordEditTextPref.setText(manetcfg.getWifiEncryptionPassword());
    }

    // wifi SSID
    EditTextPreference wifiSsidEditTextPref = (EditTextPreference) findPreference("ssidpref");
    Validation.setupWifiSsidValidator(wifiSsidEditTextPref);
    wifiSsidEditTextPref.setText(manetcfg.getWifiSsid());

    // wifi channel
    ListPreference channelpref = (ListPreference) findPreference("channelpref");
    channelpref.setEnabled(false); // TODO: disable until tested
    String[] channelStrValues = WifiChannelEnum.stringValues();
    String[] channelDescValues = WifiChannelEnum.descriptionValues();
    // remove auto channel option if not supported by device
    if (!manetcfg.getWifiDriver().startsWith("softap")
            || !manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
        // auto channel option at first index
        String[] newChannelStrValues = new String[channelStrValues.length - 1];
        String[] newChannelDescValues = new String[channelStrValues.length - 1];
        for (int i = 1; i < channelStrValues.length; i++) {
            newChannelStrValues[i - 1] = channelStrValues[i];
            newChannelDescValues[i - 1] = channelDescValues[i];
        }
        channelpref.setEntries(newChannelDescValues);
        channelpref.setEntryValues(newChannelStrValues);
        WifiChannelEnum wifiChannel = manetcfg.getWifiChannel();
        if (wifiChannel == WifiChannelEnum.AUTO) {
            channelpref.setValueIndex(WifiChannelEnum.CHANNEL_1.ordinal() - 1);
        } else {
            channelpref.setValueIndex(wifiChannel.ordinal() - 1);
        }
    } else {
        channelpref.setEntries(channelDescValues);
        channelpref.setEntryValues(channelStrValues);
        channelpref.setValueIndex(manetcfg.getWifiChannel().ordinal());
    }

    // wifi transmit power
    ListPreference txpowerPreference = (ListPreference) findPreference("txpowerpref");
    if (!manetcfg.isTransmitPowerSupported()) { // DEBUG
        if (txpowerPreference != null) {
            wifiGroupPref.removePreference(txpowerPreference);
        }
    } else {
        txpowerPreference.setEntries(WifiTxpowerEnum.descriptionValues());
        txpowerPreference.setEntryValues(WifiTxpowerEnum.stringValues());
        txpowerPreference.setValueIndex(manetcfg.getWifiTxpower().ordinal());
    }

    // bluetooth group        
    // disable bluetooth adhoc if not supported by the kernel
    if (true) { // !manetcfg.isBluetoothSupported() // TODO: disable until tested
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        btGroup.setEnabled(false);
    }

    // bluetooth
    // NOTE: bluetooth dependencies are specified in the layout XML
    // CheckBoxPreference bluetoothCheckboxPref = (CheckBoxPreference)findPreference("bluetoothonpref");

    // bluetooth keep wifi
    CheckBoxPreference btKeepWifiCheckBoxPref = (CheckBoxPreference) findPreference("bluetoothkeepwifipref");
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.ECLAIR) {
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        if (btKeepWifiCheckBoxPref != null) {
            btGroup.removePreference(btKeepWifiCheckBoxPref);
        }
    } else {
        btKeepWifiCheckBoxPref.setChecked(!manetcfg.isWifiDisabledWhenUsingBluetooth());
    }

    // bluetooth discoverable
    CheckBoxPreference btdiscoverablePreference = (CheckBoxPreference) findPreference(
            "bluetoothdiscoverablepref");
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.ECLAIR) {
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        if (btdiscoverablePreference != null) {
            btGroup.removePreference(btdiscoverablePreference);
        }
    } else {
        btdiscoverablePreference.setChecked(manetcfg.isBluetoothDiscoverableWhenInAdhocMode());
    }

    // ip address
    EditTextPreference ipAddressEditTextPref = (EditTextPreference) findPreference("ippref");
    Validation.setupIpAddressValidator(ipAddressEditTextPref);
    ipAddressEditTextPref.setText(manetcfg.getIpAddress());

    // dns server
    EditTextPreference dnsServerEditTextPref = (EditTextPreference) findPreference("dnspref");
    Validation.setupIpAddressValidator(dnsServerEditTextPref);
    dnsServerEditTextPref.setText(manetcfg.getDnsServer());

    // routing protocol
    String currRoutingProtocol = manetcfg.getRoutingProtocol();
    List<String> routingProtocolList = CoreTask.getRoutingProtocols();
    String[] routingProtocols = new String[routingProtocolList.size()];
    routingProtocolList.toArray(routingProtocols);

    ListPreference routingProtocolPreference = (ListPreference) findPreference("routingprotocolpref");
    routingProtocolPreference.setEntries(routingProtocols);
    routingProtocolPreference.setEntryValues(routingProtocols);
    routingProtocolPreference.setValue(currRoutingProtocol);

    // routing ignore list
    JSONArray array = new JSONArray(manetcfg.getRoutingIgnoreList());
    sharedPreferences.edit().putString("ignorepref", array.toString()).commit();

    // wifi interface
    String currInterface = manetcfg.getWifiInterface();
    String defaultInterface = DeviceConfig.getWifiInterface(manetcfg.getDeviceType());
    List<String> interfaceList = CoreTask.getNetworkInterfaces();
    if (!interfaceList.contains(defaultInterface)) {
        interfaceList.add(defaultInterface);
    }
    String[] interfaces = new String[interfaceList.size()];
    interfaceList.toArray(interfaces);

    ListPreference interfacePreference = (ListPreference) findPreference("interfacepref");
    interfacePreference.setEntries(interfaces);
    interfacePreference.setEntryValues(interfaces);

    if (interfaceList.contains(currInterface)) {
        interfacePreference.setValue(currInterface);
    } else {
        interfacePreference.setValue(defaultInterface);
        currInterface = defaultInterface;
    }

    // routing gateway
    String currGatewayInterface = manetcfg.getGatewayInterface();
    interfaceList.remove(currInterface); // remove ad-hoc interface
    interfaceList.add(0, ManetConfig.GATEWAY_INTERFACE_NONE);
    interfaces = new String[interfaceList.size()];
    interfaceList.toArray(interfaces);

    ListPreference gatewayPreference = (ListPreference) findPreference("gatewaypref");
    gatewayPreference.setEntries(interfaces);
    gatewayPreference.setEntryValues(interfaces);
    gatewayPreference.setValue(currGatewayInterface);

    if (interfaceList.contains(currGatewayInterface)) {
        gatewayPreference.setValue(currGatewayInterface);
    } else {
        gatewayPreference.setValue(ManetConfig.GATEWAY_INTERFACE_NONE);
    }

    // screen on
    CheckBoxPreference screenOnPreference = (CheckBoxPreference) findPreference("screenonpref");
    screenOnPreference.setChecked(manetcfg.isScreenOnWhenInAdhocMode());

    // battery temperature

    setupFlag = true;
}

From source file:co.taqat.call.AccountPreferencesFragment.java

private void initializeTransportPreference(ListPreference pref) {
    List<CharSequence> entries = new ArrayList<CharSequence>();
    List<CharSequence> values = new ArrayList<CharSequence>();
    entries.add(getString(R.string.pref_transport_udp));
    values.add(getString(R.string.pref_transport_udp_key));
    entries.add(getString(R.string.pref_transport_tcp));
    values.add(getString(R.string.pref_transport_tcp_key));

    if (!getResources().getBoolean(R.bool.disable_all_security_features_for_markets)) {
        entries.add(getString(R.string.pref_transport_tls));
        values.add(getString(R.string.pref_transport_tls_key));
    }/*www.  ja v a2 s  . c o  m*/
    setListPreferenceValues(pref, entries, values);

    if (!isNewAccount) {
        pref.setSummary(mPrefs.getAccountTransportString(n));
        pref.setDefaultValue(mPrefs.getAccountTransportKey(n));
        pref.setValueIndex(entries.indexOf(mPrefs.getAccountTransportString(n)));
    } else {

        pref.setSummary(getString(R.string.pref_transport_udp));
        pref.setDefaultValue(getString(R.string.pref_transport_udp));
        pref.setValueIndex(entries.indexOf(getString(R.string.pref_transport_udp)));
    }
}

From source file:it.feio.android.omninotes.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override//from   w  w w.j av  a  2  s . c  om
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    this::importNotes);

            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            BaseActivity.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            OmniNotes.updateLanguage(getActivity(), value.toString());
            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName;
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING,
                                    "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}

From source file:com.dycody.android.idealnote.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override//from   ww w  . j  av  a2  s.  c o m
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {
            importNotes();
            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            PasswordHelper.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            IdealNote.updateLanguage(getActivity(), value.toString());
            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName + getString(R.string.version_postfix);
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}