Example usage for android.preference ListPreference setOnPreferenceChangeListener

List of usage examples for android.preference ListPreference setOnPreferenceChangeListener

Introduction

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

Prototype

public void setOnPreferenceChangeListener(OnPreferenceChangeListener onPreferenceChangeListener) 

Source Link

Document

Sets the callback to be invoked when this Preference is changed by the user (but before the internal state has been updated).

Usage

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();/*from   w w w. j  av a 2s  .c  o m*/
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:com.juegoteca.actividades.Opciones.java

/**
 * Shows the simplified settings UI if the device configuration if the
 * device configuration dictates that a simplified, single-pane UI should be
 * shown./* w  w  w.  j  a  v a2s .c o m*/
 */
@SuppressWarnings("deprecation")
private void setupSimplePreferencesScreen() {
    if (!isSimplePreferences(this)) {
        return;
    }

    final SharedPreferences settings = getSharedPreferences("UserInfo", 0);

    // In the simplified UI, fragments are not used at all and we instead
    // use the older PreferenceActivity APIs.

    addPreferencesFromResource(R.xml.pref_container);

    // Add 'general' preferences.
    PreferenceCategory fakeHeader = new PreferenceCategory(this);
    fakeHeader.setTitle(R.string.pref_header_general);
    getPreferenceScreen().addPreference(fakeHeader);
    addPreferencesFromResource(R.xml.pref_general);

    CheckBoxPreference preferenciaOrden = (CheckBoxPreference) findPreference("orden_ultimos_anadidos");
    preferenciaOrden.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("orden_ultimos_fecha_compra", true);
                editor.commit();
            } else {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("orden_ultimos_fecha_compra", false);
                editor.commit();
            }
            return true;
        }
    });

    ListPreference preferenciaModeda = (ListPreference) findPreference("currencys");
    preferenciaModeda.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {

            SharedPreferences.Editor editor = settings.edit();
            editor.putString("currency", newValue.toString());
            editor.commit();

            return true;
        }
    });

    CheckBoxPreference preferenciaDetalle = (CheckBoxPreference) findPreference("detalle_imagen");
    preferenciaDetalle.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("detalle_imagen", true);
                editor.commit();
            } else {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("detalle_imagen", false);
                editor.commit();
            }
            return true;
        }
    });

    SwitchPreference preferenciaTwitter = (SwitchPreference) findPreference("twitter");
    preferenciaTwitter.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue instanceof Boolean) {
                boolean isChecked = (boolean) newValue;
                if (isChecked) {
                    Intent intent = new Intent(getApplicationContext(), TwitterActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
            return true;
        }
    });

    // Add 'data and sync' preferences, and a corresponding header.
    PreferenceCategory fakeHeader2 = new PreferenceCategory(this);
    fakeHeader2.setTitle(R.string.pref_header_data);
    getPreferenceScreen().addPreference(fakeHeader2);
    addPreferencesFromResource(R.xml.pref_datos_seguridad);

    // Establece las acciones al hacer click en las preferencias
    Preference preferenciaCopiaExportar = findPreference("exportar_copia_seguridad");
    preferenciaCopiaExportar.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            Toast t;
            if (!utilidades.baseDatosEsVacia()) {
                new CopiaSeguridadFichero().execute();
            } else {
                t = Toast.makeText(getApplicationContext(), getString(R.string.no_data_backup),
                        Toast.LENGTH_SHORT);
                t.show();
            }
            return true;
        }
    });

    Preference preferenciaCopiaImportar = findPreference("importar_restaurar_seguridad");

    preferenciaCopiaImportar.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {

            AlertDialog.Builder builder = new AlertDialog.Builder(Opciones.this);
            builder.setMessage(R.string.alerta_restaurar_texto).setTitle(R.string.alerta_restaurar_titulo);
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/zip");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(Intent.createChooser(intent, "Escoja el fichero de copia..."),
                            FILE_SELECT_CODE);

                }
            });

            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                    return;
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

            return true;
        }
    });

    Preference preferenciaBorrar = findPreference("borrar_todo");
    preferenciaBorrar.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            utilidades.borrarTodosDatos(true);
            return true;
        }
    });

    // Add 'otros' preferences.
    PreferenceCategory fakeHeader3 = new PreferenceCategory(this);
    fakeHeader3.setTitle(R.string.pref_header_otros);
    getPreferenceScreen().addPreference(fakeHeader3);
    addPreferencesFromResource(R.xml.pref_otros);

    Resources res = getResources();
    // String versionName = res.getString(R.string.app_version);

    String versionName = "";
    try {
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        // versionName = res.getString(R.string.app_version);
    }

    String version = res.getString(R.string.pref_title_version, versionName);
    Preference preferenciaInicioSesion = findPreference("about");
    preferenciaInicioSesion.setTitle(version);

    Preference preferenciaLicencia = findPreference("licenses");
    preferenciaLicencia.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(getApplicationContext(), AcercaDe.class);
            startActivity(intent);
            return true;
        }
    });

}

From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPreferenceManager().setSharedPreferencesName(SharedPreferencesUtil.FILE_NAME);
    addPreferencesFromResource(R.xml.preferences);

    String downloadPath = DownloadManager.getDownloadPath();
    if (downloadPath != null) {
        String displayPath = Uri.decode(downloadPath);
        getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath);
    }/*  w  w w.  j  av a2 s  . c om*/
    ListPreference listPreference = (ListPreference) getPreferenceManager()
            .findPreference(KEY_PREF_VIEW_DIRECTION);
    CharSequence[] entries = listPreference.getEntries();
    int i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);
    listPreference = (ListPreference) getPreferenceManager().findPreference(KEY_PREF_VIEW_VIDEO_PLAYER);
    entries = listPreference.getEntries();
    i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);

    getPreferenceScreen().setOnPreferenceChangeListener(this);
    final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
            .initialDirectory((downloadPath.startsWith("/")) ? downloadPath : DownloadManager.DEFAULT_PATH)
            .newDirectoryName("download").allowNewDirectoryNameModification(true).build();
    mDialog = DirectoryChooserFragment.newInstance(config);
    mDialog.setTargetFragment(this, 0);

    float size = (float) Fresco.getImagePipelineFactory().getMainFileCache().getSize() / ByteConstants.MB;
    Preference cacheCleanPreference = getPreferenceManager().findPreference(KEY_PREF_CACHE_CLEAN);
    cacheCleanPreference.setSummary(String.format(" %.2f MB", size));

    LongClickPreference prefDownloadPath = (LongClickPreference) getPreferenceManager()
            .findPreference(KEY_PREF_DOWNLOAD_PATH);
    prefDownloadPath.setOnLongClickListener(v -> {
        new AlertDialog.Builder(activity).setTitle("?")
                .setItems(new String[] { "", "" },
                        (dialogInterface, pos) -> {
                            if (pos == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                                try {
                                    startActivityForResult(intent, RESULT_CHOOSE_DIRECTORY);
                                } catch (ActivityNotFoundException e) {
                                    e.printStackTrace();
                                    mDialog.show(getFragmentManager(), null);
                                }
                                new Handler().postDelayed(() -> {
                                    if (!opened)
                                        activity.showSnackBar(
                                                "?");
                                }, 1000);
                            } else if (pos == 1) {
                                mDialog.show(getFragmentManager(), null);
                            } else
                                activity.showSnackBar("???");
                        })
                .setNegativeButton(getString(R.string.cancel), null).show();
        return true;
    });
}

From source file:com.ichi2.anki.PreferenceContext.java

private void initSubscreen(String action, PreferenceContext listener) {
    PreferenceScreen screen;//from  ww  w. j a  v a2  s  .c om
    switch (action) {
    case "com.ichi2.anki.prefs.general":
        listener.addPreferencesFromResource(R.xml.preferences_general);
        screen = listener.getPreferenceScreen();
        // Build languages
        initializeLanguageDialog(screen);
        break;
    case "com.ichi2.anki.prefs.reviewing":
        listener.addPreferencesFromResource(R.xml.preferences_reviewing);
        screen = listener.getPreferenceScreen();
        // Show error toast if the user tries to disable answer button without gestures on
        ListPreference fullscreenPreference = (ListPreference) screen.findPreference("fullscreenMode");
        fullscreenPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            public boolean onPreferenceChange(Preference preference, final Object newValue) {
                SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(Preferences.this);
                if (prefs.getBoolean("gestures", false) || !newValue.equals("2")) {
                    return true;
                } else {
                    Toast.makeText(getApplicationContext(), R.string.full_screen_error_gestures,
                            Toast.LENGTH_LONG).show();
                    return false;
                }
            }
        });
        break;
    case "com.ichi2.anki.prefs.fonts":
        listener.addPreferencesFromResource(R.xml.preferences_fonts);
        screen = listener.getPreferenceScreen();
        initializeCustomFontsDialog(screen);
        break;
    case "com.ichi2.anki.prefs.gestures":
        listener.addPreferencesFromResource(R.xml.preferences_gestures);
        break;
    case "com.ichi2.anki.prefs.advanced":
        listener.addPreferencesFromResource(R.xml.preferences_advanced);
        screen = listener.getPreferenceScreen();
        // Check that input is valid before committing change in the collection path
        EditTextPreference collectionPathPreference = (EditTextPreference) screen.findPreference("deckPath");
        collectionPathPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            public boolean onPreferenceChange(Preference preference, final Object newValue) {
                final String newPath = (String) newValue;
                try {
                    CollectionHelper.initializeAnkiDroidDirectory(newPath);
                    return true;
                } catch (StorageAccessException e) {
                    Timber.e(e, "Could not initialize directory: %s", newPath);
                    Toast.makeText(getApplicationContext(), R.string.dialog_collection_path_not_dir,
                            Toast.LENGTH_LONG).show();
                    return false;
                }
            }
        });
        // Force full sync option
        Preference fullSyncPreference = screen.findPreference("force_full_sync");
        fullSyncPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                // TODO: Could be useful to show the full confirmation dialog
                getCol().modSchemaNoCheck();
                getCol().setMod();
                Toast.makeText(getApplicationContext(), android.R.string.ok, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        // Workaround preferences
        removeUnnecessaryAdvancedPrefs(screen);
        break;
    }
}

From source file:com.nttec.everychan.chans.dobrochan.DobroModule.java

private void addRatingPreference(PreferenceGroup group) {
    Context context = group.getContext();
    Preference.OnPreferenceChangeListener updateRatingListener = new Preference.OnPreferenceChangeListener() {
        @Override/*ww  w  .  j  a  v a 2s . c o m*/
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals(getSharedKey(PREF_KEY_MAX_RATING))) {
                setMaxRating((String) newValue);
                return true;
            }
            return false;
        }
    };
    ListPreference ratingPref = new LazyPreferences.ListPreference(context);
    ratingPref.setTitle(R.string.dobrochan_prefs_max_rating);
    ratingPref.setSummary(preferences.getString(getSharedKey(PREF_KEY_MAX_RATING), "R-15"));
    ratingPref.setEntries(RATINGS);
    ratingPref.setEntryValues(RATINGS);
    ratingPref.setDefaultValue("R-15");
    ratingPref.setKey(getSharedKey(PREF_KEY_MAX_RATING));
    ratingPref.setOnPreferenceChangeListener(updateRatingListener);
    group.addPreference(ratingPref);
}

From source file:com.nttec.everychan.chans.ponyach.PonyachModule.java

@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    ListPreference captchaLevel = new LazyPreferences.ListPreference(context);
    captchaLevel.setTitle(R.string.ponyach_prefs_captcha);
    captchaLevel.setDialogTitle(R.string.ponyach_prefs_captcha);
    captchaLevel.setKey(getSharedKey(PREF_KEY_CAPTCHA_LEVEL));
    captchaLevel.setEntryValues(new String[] { "3", "2", "1" });
    captchaLevel.setEntries(new String[] { "Easy", "Easy++", "Medium" });
    captchaLevel.setDefaultValue("1");
    preferenceGroup.addPreference(captchaLevel);

    EditTextPreference passcodePref = new EditTextPreference(context);
    passcodePref.setTitle(R.string.ponyach_prefs_passcode);
    passcodePref.setDialogTitle(R.string.ponyach_prefs_passcode);
    passcodePref.getEditText().setFilters(new InputFilter[] { new InputFilter.LengthFilter(6) });
    passcodePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override/* w  ww . j av a2s  .com*/
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            final String newPasscode = (String) newValue;
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        String url = getUsingUrl() + "passcode.php";
                        List<BasicNameValuePair> pairs = Collections
                                .singletonList(new BasicNameValuePair("passcode_just_set", newPasscode));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, null,
                                passAuthTask, false);
                        savePhpCookies();
                    } catch (final Exception e) {
                        if (context instanceof Activity) {
                            ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String message = e.getMessage() == null
                                            ? resources.getString(R.string.error_unknown)
                                            : e.getMessage();
                                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }
            });
            return false;
        }
    });
    preferenceGroup.addPreference(passcodePref);

    ListPreference domainPref = new LazyPreferences.ListPreference(context);
    domainPref.setTitle(R.string.pref_domain);
    domainPref.setDialogTitle(R.string.pref_domain);
    domainPref.setKey(getSharedKey(PREF_KEY_DOMAIN));
    domainPref.setEntryValues(DOMAINS);
    domainPref.setEntries(DOMAINS);
    domainPref.setDefaultValue(DEFAULT_DOMAIN);
    domainPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            loadPhpCookies((String) newValue);
            return true;
        }
    });
    preferenceGroup.addPreference(domainPref);

    addHttpsPreference(preferenceGroup, useHttpsDefaultValue());
    addProxyPreferences(preferenceGroup);
    captchaLevel.setSummary(captchaLevel.getEntry());
    domainPref.setSummary(domainPref.getEntry());
}

From source file:com.olearyp.gusto.Expsetup.java

/** Called when the activity is first created. */
@Override// ww w . ja v a  2 s  .  c o  m
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    settings = getSharedPreferences("serverState", MODE_PRIVATE);
    addPreferencesFromResource(R.xml.preferences);
    final Map<String, String> config = getCurrentConfig();

    // Tack version number on to titlebar at top level
    try {
        this.setTitle(getTitle() + " v" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
    } catch (final NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String ramhack_file;
    // ROM-specific settings
    if (config.get("GLB_EP_VERSION_EPDATA").contains("-TMO")) {
        findPreference("launcher").setEnabled(false);
        findPreference("phone").setEnabled(false);
        findPreference("contacts").setEnabled(false);
        findPreference("teeter").setEnabled(false);
        findPreference("quickoffice").setEnabled(false);
        ramhack_file = "10mb_kernel_patch_tmo262.zip";
    } else {
        ramhack_file = "10mb_kernel_patch_adp262.zip";
    }
    // QuickCommands menu
    {
        findPreference("reboot").setOnPreferenceClickListener(new RebootPreferenceListener(
                R.string.reboot_alert_title, R.string.reboot_msg, R.string.reboot));
        findPreference("reboot_recovery").setOnPreferenceClickListener(new RebootPreferenceListener(
                R.string.reboot_alert_title, R.string.reboot_recovery_msg, R.string.reboot_recovery));
        findPreference("reboot_bootloader").setOnPreferenceClickListener(new RebootPreferenceListener(
                R.string.reboot_alert_title, R.string.reboot_bootloader_msg, R.string.reboot_bootload));
        findPreference("reboot_poweroff").setOnPreferenceClickListener(new RebootPreferenceListener(
                R.string.shutdown_alert_title, R.string.shutdown_msg, R.string.shutdown));
        findPreference("rwsystem").setOnPreferenceClickListener(
                new ExpPreferenceListener(R.string.rwsystem, "setting /system read-write"));
        findPreference("rosystem").setOnPreferenceClickListener(
                new ExpPreferenceListener(R.string.rosystem, "setting /system read-only"));
    }
    // CPU options
    {
        findPreference("freq_sample").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | set_ep_cyan_ond_mod", "setting frequency scaling"));
        ((CheckBoxPreference) findPreference("freq_sample"))
                .setChecked(isTrueish(config, "GLB_EP_ENABLE_CYAN_OND_MOD"));
        final List<String> freqs = Arrays.asList(getResources().getStringArray(R.array.cpu_freqs_str));
        final ListPreference minFreqPref = (ListPreference) findPreference("cpu_freq_min");
        final ListPreference maxFreqPref = (ListPreference) findPreference("cpu_freq_max");
        minFreqPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(final Preference preference, final Object newValue) {
                sendCommand("GLB_EP_MIN_CPU=" + newValue.toString() + " && " + "write_out_ep_config && "
                        + "echo \"$GLB_EP_MIN_CPU\" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq",
                        "setting minimum CPU frequency", "none");
                final String[] legalfreqs = freqs.subList(freqs.indexOf(newValue), freqs.size())
                        .toArray(new String[0]);
                maxFreqPref.setEntries(legalfreqs);
                maxFreqPref.setEntryValues(legalfreqs);
                return true;
            }
        });
        maxFreqPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(final Preference preference, final Object newValue) {
                sendCommand("GLB_EP_MAX_CPU=" + newValue.toString() + " && " + "write_out_ep_config && "
                        + "echo \"$GLB_EP_MAX_CPU\" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq",
                        "setting maximum CPU frequency", "none");
                final String[] legalfreqs = freqs.subList(0, freqs.indexOf(newValue) + 1)
                        .toArray(new String[0]);
                minFreqPref.setEntries(legalfreqs);
                minFreqPref.setEntryValues(legalfreqs);
                return true;
            }
        });
        final String[] maxfreqs = freqs.subList(freqs.indexOf(config.get("GLB_EP_MIN_CPU")), freqs.size())
                .toArray(new String[0]);
        maxFreqPref.setEntries(maxfreqs);
        maxFreqPref.setEntryValues(maxfreqs);
        final String[] minfreqs = freqs.subList(0, freqs.indexOf(config.get("GLB_EP_MAX_CPU")) + 1)
                .toArray(new String[0]);
        minFreqPref.setEntries(minfreqs);
        minFreqPref.setEntryValues(minfreqs);
        maxFreqPref.setValue(config.get("GLB_EP_MAX_CPU"));
        minFreqPref.setValue(config.get("GLB_EP_MIN_CPU"));
    }
    // Downloadables
    {
        DownloadPreference p;
        p = ((DownloadPreference) findPreference("ramhack_kernel"));
        p.setParams(ASPIN_URL + "RESOURCE/" + ramhack_file, "/sdcard/" + ramhack_file);
        p.setOnPreferenceClickListener(new RamhackPreferenceListener(testRamhack(config), p));
        p = ((DownloadPreference) findPreference("kernel_mods"));
        p.setParams(ASPIN_URL + "ROM/kmods_v211_vsapp.zip", "/sdcard/epvsapps/available/kmods_v211_vsapp.zip");
        p.setOnPreferenceClickListener(new VsappPreferenceListener(
                new File("/sdcard/epvsapps/available/kmods_v211_vsapp.zip").exists(), p));
        p = ((DownloadPreference) findPreference("teeter"));
        p.setParams(ASPIN_URL + "APPS/teeter_vsapp.zip", "/sdcard/epvsapps/available/teeter_vsapp.zip");
        p.setOnPreferenceClickListener(new VsappPreferenceListener(
                new File("/sdcard/epvsapps/available/teeter_vsapp.zip").exists(), p));
        p = ((DownloadPreference) findPreference("quickoffice"));
        p.setParams(ASPIN_URL + "APPS/quickoffice_vsapp.zip",
                "/sdcard/epvsapps/available/quickoffice_vsapp.zip");
        p.setOnPreferenceClickListener(new VsappPreferenceListener(
                new File("/sdcard/epvsapps/available/quickoffice_vsapp.zip").exists(), p));
        p = ((DownloadPreference) findPreference("ext_widgets"));
        p.setParams(ASPIN_URL + "APPS/widgetpack_v2_vsapp.zip",
                "/sdcard/epvsapps/available/widgetpack_v2_vsapp.zip");
        p.setOnPreferenceClickListener(new VsappPreferenceListener(
                new File("/sdcard/epvsapps/available/widgetpack_v2_vsapp.zip").exists(), p));
        p = ((DownloadPreference) findPreference("xdan_java"));
        p.setParams(ASPIN_URL + "APPS/jbed_vsapp.zip", "/sdcard/epvsapps/available/jbed_vsapp.zip");
        p.setOnPreferenceClickListener(
                new VsappPreferenceListener(new File("/sdcard/epvsapps/available/jbed_vsapp.zip").exists(), p));
        p = ((DownloadPreference) findPreference("iwnn_ime_jp"));
        p.setParams(ASPIN_URL + "APPS/iwnnime_vsapp.zip", "/sdcard/epvsapps/available/iwnnime_vsapp.zip");
        p.setOnPreferenceClickListener(new VsappPreferenceListener(
                new File("/sdcard/epvsapps/available/iwnnime_vsapp.zip").exists(), p));
    }
    // Theme profile settings
    {
        findPreference("launcher").setOnPreferenceChangeListener(
                new ExpThemeProfileChangeListener("Launcher.apk", "changing Launcher"));
        ((CheckBoxPreference) findPreference("launcher")).setChecked(isTrueish(config, "Launcher.apk"));
        findPreference("phone").setOnPreferenceChangeListener(
                new ExpThemeProfileChangeListener("Phone.apk", "changing Phone"));
        ((CheckBoxPreference) findPreference("phone")).setChecked(isTrueish(config, "Phone.apk"));
        findPreference("contacts").setOnPreferenceChangeListener(
                new ExpThemeProfileChangeListener("Contacts.apk", "changing Contacts"));
        ((CheckBoxPreference) findPreference("contacts")).setChecked(isTrueish(config, "Contacts.apk"));
        findPreference("browser").setOnPreferenceChangeListener(
                new ExpThemeProfileChangeListener("Browser.apk", "changing the Browser"));
        ((CheckBoxPreference) findPreference("browser")).setChecked(isTrueish(config, "Browser.apk"));
        findPreference("mms")
                .setOnPreferenceChangeListener(new ExpThemeProfileChangeListener("Mms.apk", "changing MMS"));
        ((CheckBoxPreference) findPreference("mms")).setChecked(isTrueish(config, "Mms.apk"));
    }
    // Advanced Options
    {
        // Swappiness
        findPreference("swappiness").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(final Preference preference, final Object newValue) {
                sendCommand("yes '" + newValue.toString() + "' | set_ep_swappiness", "setting swappiness",
                        "none");
                return true;
            }
        });
        ((EditTextPreference) findPreference("swappiness")).setText(config.get("GLB_EP_SWAPPINESS"));
        ((EditTextPreference) findPreference("swappiness")).getEditText()
                .setKeyListener(new SwappinessKeyListener());
        // Compcache
        findPreference("compcache").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | toggle_ep_compcache", "setting compcache", true));
        ((CheckBoxPreference) findPreference("compcache"))
                .setChecked(isTrueish(config, "GLB_EP_ENABLE_COMPCACHE"));
        // Linux swap
        findPreference("linux_swap").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | toggle_ep_linuxswap", "setting Linux-swap"));
        ((CheckBoxPreference) findPreference("linux_swap"))
                .setChecked(isTrueish(config, "GLB_EP_ENABLE_LINUXSWAP"));
        // userinit.sh
        findPreference("userinit").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | toggle_ep_userinit", "setting userinit"));
        ((CheckBoxPreference) findPreference("userinit")).setChecked(isTrueish(config, "GLB_EP_RUN_USERINIT"));
        // Remove odex on boot
        findPreference("odex").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | toggle_ep_odex_boot_removal", "setting ODEX removal"));
        ((CheckBoxPreference) findPreference("odex")).setChecked(isTrueish(config, "GLB_EP_ODEX_BOOT_REMOVAL"));
        // Odex now
        findPreference("reodex").setOnPreferenceClickListener(
                new ExpPreferenceListener("yes | odex_ep_data_apps", "re-ODEXing apps"));
        // Set pid priorities
        findPreference("pid_prioritize").setOnPreferenceChangeListener(
                new ExpPreferenceListener("yes | toggle_ep_pid_prioritizer", "setting PID prioritizer"));
        ((CheckBoxPreference) findPreference("pid_prioritize"))
                .setChecked(isTrueish(config, "GLB_EP_PID_PRIORITIZE"));
    }
    // Generate and send ep_log
    findPreference("ep_log").setOnPreferenceClickListener(new EpLogListener());
}

From source file:com.cesarsk.say_it.ui.fragments.SettingsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    // Use an activity context to get the rewarded video instance.
    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getActivity());
    mRewardedVideoAd.setRewardedVideoAdListener(this);

    loadRewardedVideoAd();/*  w w  w  .  ja  v  a  2  s.c  o  m*/

    PackageInfo pInfo = null;
    try {
        pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String version = pInfo.versionName;
    final Preference app_version = getPreferenceManager().findPreference("app_version");
    app_version.setSummary("Version: " + version + " (Click for Privacy Policy)");

    final Context context = getActivity();

    if (context instanceof Callback) {
        mCallback = (Callback) context;
    } else {
        throw new IllegalStateException("Owner must implement URLCallback interface");
    }

    // add listeners for non-default actions
    Preference preference = findPreference(KEY_1);
    preference.setOnPreferenceClickListener(this);

    Preference open_source_licenses = findPreference(KEY_2);
    open_source_licenses.setOnPreferenceClickListener(this);

    Preference rate_us = getPreferenceManager().findPreference("rate_us");
    rate_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            rateUs(getActivity());
            return false;
        }
    });

    Preference contact_us = getPreferenceManager().findPreference("contact_us");
    contact_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            shareToMail(emails, "[CONTACT US - SAY IT!]", getActivity());
            return false;
        }
    });

    Preference bug_report = getPreferenceManager().findPreference("bug_report");
    bug_report.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            shareToMail(emails, "[CONTACT US - SAY IT!]", getActivity());
            return false;
        }
    });

    Preference donate_ad = getPreferenceManager().findPreference("donation_ad");
    donate_ad.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            //Launch AD
            if (mRewardedVideoAd.isLoaded()) {
                mRewardedVideoAd.show();
            }
            return false;
        }
    });

    final Preference about_us = getPreferenceManager().findPreference("about_us");
    about_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://lucacesaranoblog.wordpress.com/2017/07/18/about-us/");
            return false;
        }
    });

    final Preference eula = getPreferenceManager().findPreference("eula");
    eula.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(),
                    "https://lucacesaranoblog.wordpress.com/2017/04/28/say-it-eula-agreement/");
            return false;
        }
    });

    /*final Preference github = getPreferenceManager().findPreference("github");
    github.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Utility.openURL(getActivity(), "https://github.com/Cesarsk/Say_it");
        return false;
    }
    });*/

    final Preference other_apps = getPreferenceManager().findPreference("other_apps");
    other_apps.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://play.google.com/store/apps/developer?id=Cesarsk+Dev+Team");
            return false;
        }
    });

    final Preference voice_settings = getPreferenceManager().findPreference("tts_settings");
    voice_settings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent();
            intent.setAction("com.android.settings.TTS_SETTINGS");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return false;
        }
    });

    // compute your public key and store it in base64EncodedPublicKey
    mHelper = new IabHelper(getActivity(), LCSecurity.base64EncodedPublicKey);
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                // Oh no, there was a problem.
                if (MainActivity.isLoggingEnabled)
                    Log.d("Say It!", "Problem setting up In-app Billing: " + result);
            }
            // Hooray, IAB is fully set up!
            if (MainActivity.isLoggingEnabled)
                Log.d("Say It!", "Hooray. IAB is fully set up!" + result);
        }
    });

    mIabPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        @Override
        public void onIabPurchaseFinished(IabResult result, Purchase info) {
            if (result.isFailure()) {
                Toast.makeText(getActivity(), "Purchase Failed! Perhaps have you already purchased the item?",
                        Toast.LENGTH_SHORT).show();
            } else if (info.getSku().equals(PlayActivity.no_ads_in_app)) {
                UtilitySharedPrefs.loadAdsStatus(getActivity());
                UtilitySharedPrefs.savePrefs(getActivity(), true, MainActivity.NO_ADS_STATUS_KEY);
            }
        }
    };

    mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            if (result.isFailure()) {
                if (MainActivity.isLoggingEnabled)
                    Toast.makeText(getActivity(), "Query Failed!", Toast.LENGTH_SHORT).show();
                return;
            }

            //Open Purchase Dialog
            try {
                mHelper.flagEndAsync();
                mHelper.launchPurchaseFlow(getActivity(), PlayActivity.no_ads_in_app, 64000,
                        mIabPurchaseFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                e.printStackTrace();
            }
        }
    };

    final Preference remove_ads = getPreferenceManager().findPreference("remove_ads");
    if (MainActivity.NO_ADS) {
        remove_ads.setEnabled(false);
        remove_ads.setSummary("Thank you for supporting us ?");
    } else {
        remove_ads.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                //helper to remove ads
                List<String> additionalSkuList = new ArrayList<>();
                additionalSkuList.add(PlayActivity.no_ads_in_app);
                try {
                    mHelper.flagEndAsync();
                    mHelper.queryInventoryAsync(true, additionalSkuList, mQueryFinishedListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
    }

    final Preference reset_tutorial = getPreferenceManager().findPreference("reset_showcase");
    reset_tutorial.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Random rand = new Random();
            int randomNum = rand.nextInt((10000 - 10) + 1) + 10; //(max - min) + 1 + min
            MainActivity.id_showcase_playactivity = "" + randomNum;
            Toast.makeText(getActivity(), "Tutorial has been reset", Toast.LENGTH_SHORT).show();
            //MainActivity.id_showcase_fragments = "" + randomNum2;
            //int randomNum2 = rand.nextInt((10000 - 10) + 1) + 10; //(max - min) + 1 + min //These two statements are commented because MaterialShowCase often crashes on fragments and while pressing the back button.
            return false;
        }
    });

    //setting an own Alert Dialog's title color
    final Spannable title = new SpannableString("Delete Recordings");
    title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, title.length(), 0);
    final Spannable message = new SpannableString("Are you sure you want to delete all recordings?");
    message.setSpan(new ForegroundColorSpan(Color.GRAY), 0, message.length(), 0);

    final Preference delete_recordings = getPreferenceManager().findPreference("delete_recordings");
    delete_recordings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(message)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Utility.delete_recordings(getActivity());
                            Toast.makeText(getActivity(), "Recordings deleted!", Toast.LENGTH_SHORT).show();
                        }
                    }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //do nothing
                        }
                    }).show();
            return true;
        }
    });

    final ListPreference button_vibration = (ListPreference) getPreferenceManager()
            .findPreference("button_vibration");
    button_vibration.setSummary(button_vibration.getEntry());
    final Spannable default_vibration_settings_title = new SpannableString("Vibration Settings");
    default_vibration_settings_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0,
            default_vibration_settings_title.length(), 0);
    button_vibration.setDialogTitle(default_vibration_settings_title);

    button_vibration.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_vibration = button_vibration.findIndexOfValue(new_value);
            CharSequence[] entries = button_vibration.getEntries();
            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_VIBRATION_KEY);
            button_vibration
                    .setSummary(button_vibration.getEntries()[button_vibration.findIndexOfValue(new_value)]);
            Toast.makeText(getActivity(), String.valueOf(entries[index_default_vibration]), Toast.LENGTH_SHORT)
                    .show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            return true;
        }
    });

    final ListPreference default_accent = (ListPreference) getPreferenceManager()
            .findPreference("default_accent");
    default_accent.setSummary(default_accent.getEntry());
    final Spannable default_accent_title = new SpannableString("Default Accent");
    default_accent_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, default_accent_title.length(), 0);
    default_accent.setDialogTitle(default_accent_title);

    default_accent.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_accent = default_accent.findIndexOfValue(new_value);
            CharSequence[] entries = default_accent.getEntries();

            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_ACCENT_KEY);
            default_accent.setSummary(default_accent.getEntries()[default_accent.findIndexOfValue(new_value)]);
            //Toast.makeText(getActivity(), String.valueOf(entries[index_default_accent]), Toast.LENGTH_SHORT).show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            return true;
        }
    });

    final ListPreference theme_selector = (ListPreference) getPreferenceManager()
            .findPreference("theme_selector");
    final Spannable theme_selector_title = new SpannableString("Theme");
    theme_selector_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, theme_selector_title.length(), 0);
    theme_selector.setDialogTitle(theme_selector_title);

    theme_selector.setSummary(theme_selector.getEntry());

    theme_selector.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_theme = theme_selector.findIndexOfValue(new_value);
            CharSequence[] entries = theme_selector.getEntries();
            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_THEME_KEY);
            theme_selector.setSummary(theme_selector.getEntries()[theme_selector.findIndexOfValue(new_value)]);
            //Toast.makeText(getActivity(), String.valueOf(entries[index_default_theme]), Toast.LENGTH_SHORT).show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            Toast.makeText(getActivity(), "Done! Reboot to see changes.", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

    Preference acknowledgements = getPreferenceManager().findPreference("acknowledgements");
    acknowledgements.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            final Intent preference_intent = new Intent(getActivity(), FileTextActivity.class);
            Bundle args = new Bundle();
            args.putString(FileTextActivity.PREFERENCE, "acknowledgements");
            preference_intent.putExtras(args);
            startActivity(preference_intent,
                    ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
            return false;
        }
    });

    app_version.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://lucacesaranoblog.wordpress.com/2017/04/18/privacy-policy/");
            return false;
        }
    });
}

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

@SuppressWarnings("deprecation")
@Override// w  w  w  . ja  va 2 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 -> {

            // 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  .  jav  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;
    //                }
    //            });
    //        }
}