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:com.almalence.opencam.Fragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    thiz = this;//from   www  .ja v  a  2  s.co m

    String settings = getArguments().getString("type");

    ApplicationScreen.getPluginManager().loadHeaderContent(settings, this);

    if (null == getPreferenceScreen())
        return;
    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initSummary(getPreferenceScreen().getPreference(i));
    }

    Preference nightPreference = findPreference("night");
    if (nightPreference != null) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (prefs.getBoolean("useCamera2Pref", false)) {
            getPreferenceScreen().removePreference(nightPreference);
        } else {
            Preference superPreference = findPreference("super");
            getPreferenceScreen().removePreference(superPreference);
        }
    }

    final SeekBarPreference brightnessPref = (SeekBarPreference) this.findPreference("brightnessPref");
    if (brightnessPref != null) {
        // Set seekbar summary :
        float gamma = PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat("gammaPref", 0.5f);
        brightnessPref.setSummary(
                this.getString(R.string.Pref_Super_BrightnessEnhancementValue).replace("$1", "" + gamma));
        brightnessPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            private final Map<Integer, Float> gamma_map = new HashMap<Integer, Float>() {
                {
                    put(0, 0.5f);
                    put(1, 0.55f);
                    put(2, 0.6f);
                    put(3, 0.65f);
                    put(4, 0.7f);
                }
            };

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                int radius = (Integer) newValue;
                float gamma = gamma_map.get(radius);
                PreferenceManager
                        .getDefaultSharedPreferences(Fragment.thiz.getActivity().getApplicationContext()).edit()
                        .putFloat("gammaPref", gamma).commit();
                brightnessPref.setSummary(getActivity()
                        .getString(R.string.Pref_Super_BrightnessEnhancementValue).replace("$1", "" + gamma));
                return true;
            }
        });
    }

    final CheckBoxPreference upscalePref = (CheckBoxPreference) this.findPreference("upscaleResult");
    if (upscalePref != null) {
        Size size = CameraController.getMaxCameraImageSize(CameraController.YUV);
        long resMpx = 0;
        float mpix = 0.0f;
        if (size != null) {
            resMpx = (long) ((long) size.getWidth() * (long) size.getHeight() * 2.25);
            mpix = (float) resMpx / 1000000.f;
        }

        String name = String.format("%3.1f Mpix ", mpix);

        upscalePref.setSummary(
                getActivity().getString(R.string.Pref_Super_SummaryUpscale).replace("$1", "" + name));
    }

    Preference cameraParameters = findPreference("camera_parameters");
    if (cameraParameters != null) {
        cameraParameters.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                try {
                    showCameraParameters();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return true;
            }
        });
    }

    CheckBoxPreference helpPref = (CheckBoxPreference) findPreference("showHelpPrefCommon");
    if (helpPref != null)
        helpPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                if (((CheckBoxPreference) preference).isChecked()) {
                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(MainScreen.getMainContext());
                    Editor prefsEditor = prefs.edit();
                    prefsEditor.putBoolean("droShowHelp", true);
                    prefsEditor.putBoolean("sequenceRemovalShowHelp", true);
                    prefsEditor.putBoolean("panoramaShowHelp", true);
                    prefsEditor.putBoolean("superShowHelp", true);
                    prefsEditor.putBoolean("groupshotRemovalShowHelp", true);
                    prefsEditor.putBoolean("objectRemovalShowHelp", true);
                    prefsEditor.putBoolean("bestShotShowHelp", true);
                    prefsEditor.commit();
                }

                return true;
            }
        });

    EditTextPreference prefix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPrefixValue));
    EditTextPreference postfix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPostfixValue));
    initExportName(null, null);

    if (prefix != null) {
        prefix.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                initExportName(preference, newValue);
                return true;
            }
        });
    }

    if (postfix != null) {
        postfix.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                initExportName(preference, newValue);
                return true;
            }
        });
    }

    Preference sonyPreference = findPreference(MainScreen.sSonyCamerasPref);
    if (sonyPreference != null) {
        sonyPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean sonyCamerasAvailable = (Boolean) newValue;
                if (sonyCamerasAvailable) {
                    Toast.makeText(getActivity(),
                            getActivity().getString(R.string.pref_general_more_sonyCamera_available),
                            Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

    ListPreference saveToPreference = (ListPreference) this
            .findPreference(getResources().getString(R.string.Preference_SaveToValue));

    // if android 5+, then remove "save to SD card" option. Because it's
    // equals to "save to custom folder" option.
    if (saveToPreference != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CharSequence[] entries = saveToPreference.getEntries();
        CharSequence[] entriyValues = saveToPreference.getEntryValues();

        CharSequence[] newEntries = new String[2];
        CharSequence[] newEntriyValues = new String[2];

        newEntries[0] = entries[0];
        newEntries[1] = entries[2];
        newEntriyValues[0] = entriyValues[0];
        newEntriyValues[1] = entriyValues[2];

        saveToPreference.setEntries(newEntries);
        saveToPreference.setEntryValues(newEntriyValues);
    }
    if (saveToPreference != null) {

        saveToPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                int v = -1;

                int v_old = 0;

                try {
                    v = Integer.parseInt(newValue.toString());
                    v_old = Integer.parseInt(((ListPreference) preference).getValue());
                } catch (NumberFormatException e) {

                }

                if ((v == 2 || v == 1) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        Toast.makeText(MainScreen.getInstance(),
                                MainScreen.getAppResources()
                                        .getString(R.string.pref_advanced_saving_saveToPref_CantSaveToSD),
                                Toast.LENGTH_LONG).show();

                        if (isDeviceRooted()) {
                            Intent intent = new Intent(Preferences.thiz, FolderPicker.class);

                            intent.putExtra(MainScreen.sSavePathPref, v_old);

                            Preferences.thiz.startActivity(intent);

                            return true;
                        } else
                            return false;
                    }
                }

                if (v == 2 || v == 1) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                        startActivityForResult(intent, CHOOSE_FOLDER_CODE);
                    } else if (v != 1) {
                        Intent intent = new Intent(Preferences.thiz, FolderPicker.class);

                        intent.putExtra(MainScreen.sSavePathPref, v_old);

                        Preferences.thiz.startActivity(intent);
                    }
                }

                return true;
            }
        });
    }

    PreferenceCategory cat = (PreferenceCategory) this.findPreference("Pref_VFCommon_Preference_Category");
    if (cat != null) {
        CheckBoxPreference cp = (CheckBoxPreference) cat.findPreference("maxScreenBrightnessPref");
        if (cp != null) {
            cp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    boolean value = Boolean.parseBoolean(newValue.toString());
                    setScreenBrightness(value);
                    return true;
                }
            });
        }
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
    boolean MaxScreenBrightnessPreference = prefs.getBoolean("maxScreenBrightnessPref", false);
    setScreenBrightness(MaxScreenBrightnessPreference);
}

From source file:com.nttec.everychan.chans.allchan.AllchanModule.java

@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
    Context context = preferenceGroup.getContext();
    addOnlyNewPostsPreference(preferenceGroup, true);
    final ListPreference captchaPreference = new LazyPreferences.ListPreference(context); //captcha_type
    captchaPreference.setTitle(R.string.pref_captcha_type);
    captchaPreference.setDialogTitle(R.string.pref_captcha_type);
    captchaPreference.setKey(getSharedKey(PREF_KEY_CAPTCHA_TYPE));
    captchaPreference.setEntryValues(CAPTCHA_TYPES_KEYS);
    captchaPreference.setEntries(CAPTCHA_TYPES);
    captchaPreference.setDefaultValue(CAPTCHA_TYPE_DEFAULT);
    int i = Arrays.asList(CAPTCHA_TYPES_KEYS)
            .indexOf(preferences.getString(getSharedKey(PREF_KEY_CAPTCHA_TYPE), CAPTCHA_TYPE_DEFAULT));
    if (i >= 0)
        captchaPreference.setSummary(CAPTCHA_TYPES[i]);
    preferenceGroup.addPreference(captchaPreference);
    addHttpsPreference(preferenceGroup, true);
    addCloudflareRecaptchaFallbackPreference(preferenceGroup);
    addProxyPreferences(preferenceGroup);

    final CheckBoxPreference proxyPreference = (CheckBoxPreference) preferenceGroup
            .findPreference(getSharedKey(PREF_KEY_USE_PROXY));
    proxyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override/*from  ww w.  ja v a 2s  .com*/
        public boolean onPreferenceClick(Preference preference) {
            if (proxyPreference.isChecked() && captchaPreference.getValue().equals("recaptcha")) {
                captchaPreference.setValue("recaptcha-fallback");
            }
            return false;
        }
    });
    captchaPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (proxyPreference.isChecked() && newValue.equals("recaptcha")) {
                captchaPreference.setValue("recaptcha-fallback");
                return false;
            }
            return true;
        }
    });
}

From source file:nya.miku.wishmaster.chans.tumbach.TumbachModule.java

@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
    Context context = preferenceGroup.getContext();
    addOnlyNewPostsPreference(preferenceGroup, true);
    final ListPreference captchaPreference = new LazyPreferences.ListPreference(context); //captcha_type
    captchaPreference.setTitle(R.string.pref_captcha_type);
    captchaPreference.setDialogTitle(R.string.pref_captcha_type);
    captchaPreference.setKey(getSharedKey(PREF_KEY_CAPTCHA_TYPE));
    captchaPreference.setEntryValues(CAPTCHA_TYPES_KEYS);
    captchaPreference.setEntries(CAPTCHA_TYPES);
    captchaPreference.setDefaultValue(CAPTCHA_TYPE_DEFAULT);
    int i = Arrays.asList(CAPTCHA_TYPES_KEYS)
            .indexOf(preferences.getString(getSharedKey(PREF_KEY_CAPTCHA_TYPE), CAPTCHA_TYPE_DEFAULT));
    if (i >= 0)
        captchaPreference.setSummary(CAPTCHA_TYPES[i]);
    preferenceGroup.addPreference(captchaPreference);
    addPasswordPreference(preferenceGroup);
    addHttpsPreference(preferenceGroup, true);
    addCloudflareRecaptchaFallbackPreference(preferenceGroup);
    addProxyPreferences(preferenceGroup);

    final CheckBoxPreference proxyPreference = (CheckBoxPreference) preferenceGroup
            .findPreference(getSharedKey(PREF_KEY_USE_PROXY));
    proxyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override//from   www. j av a 2s  .c o m
        public boolean onPreferenceClick(Preference preference) {
            if (proxyPreference.isChecked() && captchaPreference.getValue().equals("recaptcha")) {
                captchaPreference.setValue("recaptcha-fallback");
            }
            return false;
        }
    });
    captchaPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (proxyPreference.isChecked() && newValue.equals("recaptcha")) {
                captchaPreference.setValue("recaptcha-fallback");
                return false;
            }
            return true;
        }
    });
}

From source file:com.aware.Aware_Preferences.java

/**
 * Webservices module settings UI/*from  w  ww . j  a v  a 2s  . c o m*/
 */
private void webservices() {
    final CheckBoxPreference webservice = (CheckBoxPreference) findPreference(
            Aware_Preferences.STATUS_WEBSERVICE);
    webservice.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE).equals("true"));
    webservice.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            if (Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER).length() == 0) {
                showDialog(DIALOG_ERROR_MISSING_PARAMETERS);
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE, false);
                webservice.setChecked(false);
                return false;
            } else {
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE,
                        webservice.isChecked());
                if (webservice.isChecked()
                        && Aware.getSetting(getApplicationContext(), WEBSERVICE_SERVER).length() > 0) {
                    //setup and send data
                    Intent study_config = new Intent(getApplicationContext(), StudyConfig.class);
                    study_config.putExtra("study_url",
                            Aware.getSetting(getApplicationContext(), WEBSERVICE_SERVER));
                    startService(study_config);
                }
                return true;
            }
        }
    });

    final EditTextPreference webservice_server = (EditTextPreference) findPreference(
            Aware_Preferences.WEBSERVICE_SERVER);
    webservice_server.setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER));
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER).length() > 0) {
        webservice_server.setSummary(
                "Server: " + Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER));
    }
    webservice_server.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER, (String) newValue);
            webservice_server.setSummary("Server: " + (String) newValue);
            return true;
        }
    });

    final CheckBoxPreference webservice_wifi_only = (CheckBoxPreference) findPreference(
            Aware_Preferences.WEBSERVICE_WIFI_ONLY);
    webservice_wifi_only.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY).equals("true"));
    webservice_wifi_only.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY,
                    webservice_wifi_only.isChecked());
            return true;
        }
    });

    final EditTextPreference frequency_webservice = (EditTextPreference) findPreference(
            Aware_Preferences.FREQUENCY_WEBSERVICE);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE).length() > 0) {
        frequency_webservice.setSummary(
                Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE) + " minutes");
    }
    frequency_webservice
            .setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE));
    frequency_webservice.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE,
                    (String) newValue);
            frequency_webservice.setSummary((String) newValue + " minutes");
            return true;
        }
    });

    final ListPreference clean_old_data = (ListPreference) findPreference(FREQUENCY_CLEAN_OLD_DATA);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_CLEAN_OLD_DATA).length() > 0) {
        String freq = Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_CLEAN_OLD_DATA);
        if (freq.equals("0")) {
            clean_old_data.setSummary("Never");
        } else if (freq.equals("1")) {
            clean_old_data.setSummary("Weekly");
        } else if (freq.equals("2")) {
            clean_old_data.setSummary("Monthly");
        }
    }
    clean_old_data.setDefaultValue(Aware.getSetting(getApplicationContext(), FREQUENCY_CLEAN_OLD_DATA));
    clean_old_data.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), FREQUENCY_CLEAN_OLD_DATA, (String) newValue);
            if (((String) newValue).equals("0")) {
                clean_old_data.setSummary("Never");
            } else if (((String) newValue).equals("1")) {
                clean_old_data.setSummary("Weekly");
            } else if (((String) newValue).equals("2")) {
                clean_old_data.setSummary("Monthly");
            }
            return true;
        }
    });
}

From source file:com.p3authentication.preferences.Prefs.java

@SuppressWarnings("deprecation")
@Override/*from w  ww  .  j  a v  a2  s.  c om*/
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    addPreferencesFromResource(R.xml.pref);

    AccessPin = (EditTextPreference) getPreferenceManager().findPreference("KeypadKey");
    final Preference ResetPreference = getPreferenceManager().findPreference("reset_data");
    final Preference EULAPreference = getPreferenceManager().findPreference("eula");
    final Preference AboutUsPreference = getPreferenceManager().findPreference("about_us");
    final Preference UnlockAppsPreference = getPreferenceManager().findPreference("unlock_apps");
    final Preference TouchTolerance = getPreferenceManager().findPreference("touch_tolerance");
    final Preference RedownloadImage = getPreferenceManager().findPreference("redownload_images");
    final Preference RateApp = getPreferenceManager().findPreference("rate_app");
    final CheckBoxPreference GhostStatusPref = (CheckBoxPreference) getPreferenceManager()
            .findPreference("GhostStatus");
    final CheckBoxPreference StartServicePref = (CheckBoxPreference) getPreferenceManager()
            .findPreference("startup_service");
    final ListPreference patterntype = (ListPreference) getPreferenceManager().findPreference("PatternType");
    final ListPreference PatternStealth = (ListPreference) getPreferenceManager()
            .findPreference("PatternStealth");
    if (patterntype.getValue().toString().equals("No Pattern")) {
        PatternStealth.setEnabled(false);
    } else {
        PatternStealth.setEnabled(true);
    }

    if (GhostStatusPref.isChecked()) {
        AccessPin.setEnabled(true);
    } else {
        AccessPin.setEnabled(false);
    }
    AccessPin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // TODO Auto-generated method stub
            if (newValue.toString().trim().equals("")) {

                Toast.makeText(Prefs.this, "Your Custom PIN cannot be empty.", Toast.LENGTH_LONG).show();

                return false;
            } else if (newValue.toString().length() < 5) {
                Toast.makeText(Prefs.this, "Your Custom PIN must be atleast 5 Digits.", Toast.LENGTH_LONG)
                        .show();

                return false;
            }
            Toast.makeText(Prefs.this, "Your Custom PIN is set.", Toast.LENGTH_LONG).show();
            return true;
        }

    });
    GhostStatusPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                hideLauncherIcon();
                Toast.makeText(Prefs.this, "P3 hidden from App Menu", Toast.LENGTH_SHORT).show();
            } else {
                showLauncherIcon();
                Toast.makeText(Prefs.this, "P3 visible on App Menu", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

    });
    StartServicePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                ComponentName receiver = new ComponentName(Prefs.this, Startup.class);
                PackageManager pm = getPackageManager();

                pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP);

            } else {
                ComponentName receiver = new ComponentName(Prefs.this, Startup.class);
                PackageManager pm = getPackageManager();

                pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);
            }
            return true;
        }

    });
    patterntype.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // TODO Auto-generated method stub
            if (!newValue.toString().equals("No Pattern")) {
                PatternStealth.setEnabled(true);
            } else {
                PatternStealth.setEnabled(false);
            }
            return true;
        }
    });
    ResetPreference.setOnPreferenceClickListener(this);
    UnlockAppsPreference.setOnPreferenceClickListener(this);
    TouchTolerance.setOnPreferenceClickListener(this);
    RedownloadImage.setOnPreferenceClickListener(this);
    RateApp.setOnPreferenceClickListener(this);
    AboutUsPreference.setOnPreferenceClickListener(this);
    EULAPreference.setOnPreferenceClickListener(this);

}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Context appContext = getActivity().getApplicationContext();

    // retrieve the arguments
    Bundle args = getArguments();/* w  w w. j  a va  2 s. c o  m*/
    String matrixId = args.getString(ARG_MATRIX_ID);
    mSession = Matrix.getInstance(appContext).getSession(matrixId);

    // sanity checks
    if ((null == mSession) || !mSession.isAlive()) {
        getActivity().finish();
        return;
    }

    // define the layout
    addPreferencesFromResource(R.xml.vector_settings_preferences);

    if (null == mPushesRuleByResourceId) {
        mPushesRuleByResourceId = new HashMap<>();

        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_ALL_NOTIF_PREFERENCE_KEY,
                BingRule.RULE_ID_DISABLE_ALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_THIS_DEVICE_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_TURN_SCREEN_ON_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_DISPLAY_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_DISPLAY_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_USER_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_USER_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_ONE_TO_ONE_PREFERENCE_KEY,
                BingRule.RULE_ID_ONE_TO_ONE_ROOM);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_GROUP_CHAT_PREFERENCE_KEY,
                BingRule.RULE_ID_ALL_OTHER_MESSAGES_ROOMS);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_INVITED_TO_ROOM_PREFERENCE_KEY,
                BingRule.RULE_ID_INVITE_ME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CALL_INVITATIONS_PREFERENCE_KEY,
                BingRule.RULE_ID_CALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_SENT_BY_BOT_PREFERENCE_KEY,
                BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS);
    }

    UserAvatarPreference avatarPreference = (UserAvatarPreference) findPreference(
            PreferencesManager.SETTINGS_PROFILE_PICTURE_PREFERENCE_KEY);
    avatarPreference.setSession(mSession);
    avatarPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onUpdateAvatarClick();
            return false;
        }
    });

    EditTextPreference passwordPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CHANGE_PASSWORD_PREFERENCE_KEY);
    passwordPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onPasswordUpdateClick();
            return false;
        }
    });

    EditTextPreference notificationRingTonePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_RINGTONE_SELECTION_PREFERENCE_KEY);
    notificationRingTonePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);

            if (null != PreferencesManager.getNotificationRingTone(getActivity())) {
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                        PreferencesManager.getNotificationRingTone(getActivity()));
            }
            getActivity().startActivityForResult(intent, REQUEST_NOTIFICATION_RINGTONE);
            return false;
        }
    });
    refreshNotificationRingTone();

    EditTextPreference notificationPrivacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_PRIVACY_PREFERENCE_KEY);
    if (notificationPrivacyPreference != null) {
        notificationPrivacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(NotificationPrivacyActivity.getIntent(getActivity()));
                return true;
            }
        });
        refreshNotificationPrivacy();
    }

    // application version
    VectorCustomActionEditTextPreference versionTextPreference = (VectorCustomActionEditTextPreference) findPreference(
            PreferencesManager.SETTINGS_VERSION_PREFERENCE_KEY);
    if (null != versionTextPreference) {
        versionTextPreference.setSummary(VectorUtils.getApplicationVersion(appContext));

        versionTextPreference.setOnPreferenceLongClickListener(
                new VectorCustomActionEditTextPreference.OnPreferenceLongClickListener() {
                    @Override
                    public boolean onPreferenceLongClick(Preference preference) {
                        VectorUtils.copyToClipboard(appContext, VectorUtils.getApplicationVersion(appContext));
                        return true;
                    }
                });
    }

    // olm version
    EditTextPreference olmTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_OLM_VERSION_PREFERENCE_KEY);
    if (null != olmTextPreference) {
        olmTextPreference.setSummary(
                Matrix.getInstance(appContext).getDefaultSession().getCryptoVersion(appContext, false));
    }

    // user account
    EditTextPreference accountIdTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_LOGGED_IN_PREFERENCE_KEY);
    if (null != accountIdTextPreference) {
        accountIdTextPreference.setSummary(mSession.getMyUserId());
    }

    // home server
    EditTextPreference homeServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_HOME_SERVER_PREFERENCE_KEY);
    if (null != homeServerTextPreference) {
        homeServerTextPreference.setSummary(mSession.getHomeServerConfig().getHomeserverUri().toString());
    }

    // identity server
    EditTextPreference identityServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_IDENTITY_SERVER_PREFERENCE_KEY);
    if (null != identityServerTextPreference) {
        identityServerTextPreference
                .setSummary(mSession.getHomeServerConfig().getIdentityServerUri().toString());
    }

    // terms & conditions
    EditTextPreference termConditionsPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_APP_TERM_CONDITIONS_PREFERENCE_KEY);

    if (null != termConditionsPreference) {
        termConditionsPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppTac();
                return false;
            }
        });
    }

    // Themes
    ListPreference themePreference = (ListPreference) findPreference(ThemeUtils.APPLICATION_THEME_KEY);

    if (null != themePreference) {
        themePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                if (newValue instanceof String) {
                    VectorApp.updateApplicationTheme((String) newValue);
                    getActivity().startActivity(getActivity().getIntent());
                    getActivity().finish();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    // privacy policy
    EditTextPreference privacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_PRIVACY_POLICY_PREFERENCE_KEY);

    if (null != privacyPreference) {
        privacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppPrivacyPolicy();
                return false;
            }
        });
    }

    // third party notice
    EditTextPreference thirdPartyNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_THIRD_PARTY_NOTICES_PREFERENCE_KEY);

    if (null != thirdPartyNotices) {
        thirdPartyNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayThirdPartyLicenses();
                return false;
            }
        });
    }

    // copyright
    EditTextPreference copyrightNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_COPYRIGHT_PREFERENCE_KEY);

    if (null != copyrightNotices) {
        copyrightNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppCopyright();
                return false;
            }
        });
    }

    // update keep medias period
    final EditTextPreference keepMediaPeriodPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_MEDIA_SAVING_PERIOD_KEY);

    if (null != keepMediaPeriodPreference) {
        keepMediaPeriodPreference
                .setSummary(PreferencesManager.getSelectedMediasSavingPeriodString(getActivity()));

        keepMediaPeriodPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                new AlertDialog.Builder(getActivity())
                        .setSingleChoiceItems(PreferencesManager.getMediasSavingItemsChoicesList(getActivity()),
                                PreferencesManager.getSelectedMediasSavingPeriod(getActivity()),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int n) {
                                        PreferencesManager.setSelectedMediasSavingPeriod(getActivity(), n);
                                        d.cancel();

                                        keepMediaPeriodPreference.setSummary(PreferencesManager
                                                .getSelectedMediasSavingPeriodString(getActivity()));
                                    }
                                })
                        .show();
                return false;
            }
        });
    }

    // clear medias cache
    final EditTextPreference clearMediaCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_MEDIA_CACHE_PREFERENCE_KEY);

    if (null != clearMediaCachePreference) {
        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearMediaCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearMediaCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();

                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        mSession.getMediasCache().clear();
                        Glide.get(getActivity()).clearDiskCache();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        hideLoadingView();

                        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
                            @Override
                            public void onSuccess(Long size) {
                                clearMediaCachePreference.setSummary(
                                        android.text.format.Formatter.formatFileSize(getActivity(), size));
                            }
                        });
                    }
                };

                try {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## mSession.getMediasCache().clear() failed " + e.getMessage());
                    task.cancel(true);
                    hideLoadingView();
                }
                return false;
            }
        });
    }

    // clear cache
    final EditTextPreference clearCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_CACHE_PREFERENCE_KEY);

    if (null != clearCachePreference) {
        MXSession.getApplicationSizeCaches(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();
                Matrix.getInstance(appContext).reloadSessions(appContext);
                return false;
            }
        });
    }

    final EditTextPreference displaynamePref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DISPLAY_NAME_PREFERENCE_KEY);
    displaynamePref.setSummary(mSession.getMyUser().displayname);
    displaynamePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            onDisplayNameClick((null == newValue) ? null : ((String) newValue).trim());
            return false;
        }
    });

    final VectorSwitchPreference urlPreviewPreference = (VectorSwitchPreference) findPreference(
            PreferencesManager.SETTINGS_SHOW_URL_PREVIEW_KEY);
    urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());

    urlPreviewPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            if ((null != newValue) && ((boolean) newValue != mSession.isURLPreviewEnabled())) {
                displayLoadingView();
                mSession.setURLPreviewStatus((boolean) newValue, new ApiCallback<Void>() {
                    @Override
                    public void onSuccess(Void info) {
                        urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());
                        hideLoadingView();
                    }

                    private void onError(String errorMessage) {
                        if (null != getActivity()) {
                            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                        }
                        onSuccess(null);
                    }

                    @Override
                    public void onNetworkError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onMatrixError(MatrixError e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onUnexpectedError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }
                });
            }

            return false;
        }
    });

    // push rules
    for (String resourceText : mPushesRuleByResourceId.keySet()) {
        final Preference preference = findPreference(resourceText);

        if (null != preference) {
            if (preference instanceof CheckBoxPreference) {
                preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
                        // on some old android APIs,
                        // the callback is called even if there is no user interaction
                        // so the value will be checked to ensure there is really no update.
                        onPushRuleClick(preference.getKey(), (boolean) newValueAsVoid);
                        return true;
                    }
                });
            } else if (preference instanceof BingRulePreference) {
                final BingRulePreference bingRulePreference = (BingRulePreference) preference;
                bingRulePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        new AlertDialog.Builder(getActivity()).setSingleChoiceItems(
                                bingRulePreference.getBingRuleStatuses(),
                                bingRulePreference.getRuleStatusIndex(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int index) {
                                        BingRule rule = bingRulePreference.createRule(index);
                                        d.cancel();

                                        if (null != rule) {
                                            displayLoadingView();
                                            mSession.getDataHandler().getBingRulesManager().updateRule(
                                                    bingRulePreference.getRule(), rule,
                                                    new BingRulesManager.onBingRuleUpdateListener() {
                                                        private void onDone() {
                                                            refreshDisplay();
                                                            hideLoadingView();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateSuccess() {
                                                            onDone();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateFailure(
                                                                String errorMessage) {
                                                            if (null != getActivity()) {
                                                                Toast.makeText(getActivity(), errorMessage,
                                                                        Toast.LENGTH_SHORT).show();
                                                            }
                                                            onDone();
                                                        }
                                                    });
                                        }
                                    }
                                }).show();
                        return true;
                    }
                });
            }
        }
    }

    // background sync tuning settings
    // these settings are useless and hidden if the app is registered to the GCM push service
    final GcmRegistrationManager gcmMgr = Matrix.getInstance(appContext).getSharedGCMRegistrationManager();
    if (gcmMgr.useGCM() && gcmMgr.hasRegistrationToken()) {
        // Hide the section
        PreferenceScreen preferenceScreen = getPreferenceScreen();
        PreferenceCategory backgroundSyncCategory = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_PREFERENCE_KEY);
        PreferenceCategory backgroundSyncDivider = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_DIVIDER_PREFERENCE_KEY);

        preferenceScreen.removePreference(backgroundSyncDivider);
        preferenceScreen.removePreference(backgroundSyncCategory);
    } else {
        mSyncRequestTimeoutPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_TIMEOUT_PREFERENCE_KEY);
        mSyncRequestDelayPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_DELAY_PREFERENCE_KEY);
        final CheckBoxPreference useBackgroundSyncPref = (CheckBoxPreference) findPreference(
                PreferencesManager.SETTINGS_ENABLE_BACKGROUND_SYNC_PREFERENCE_KEY);

        if (null != useBackgroundSyncPref) {

            final GcmRegistrationManager.ThirdPartyRegistrationListener listener = new GcmRegistrationManager.ThirdPartyRegistrationListener() {

                @Override
                public void onThirdPartyRegistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyRegistrationFailed() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistrationFailed() {
                    hideLoadingView();
                }
            };

            if (null != useBackgroundSyncPref) {
                useBackgroundSyncPref.setChecked(gcmMgr.isBackgroundSyncAllowed());

                useBackgroundSyncPref
                        .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                            @Override
                            public boolean onPreferenceChange(Preference preference, Object aNewValue) {
                                final boolean newValue = (boolean) aNewValue;

                                if (newValue != gcmMgr.isBackgroundSyncAllowed()) {
                                    gcmMgr.setBackgroundSyncAllowed(newValue);
                                }

                                displayLoadingView();

                                Matrix.getInstance(VectorSettingsPreferencesFragment.this.getActivity())
                                        .getSharedGCMRegistrationManager().forceSessionsRegistration(listener);

                                return true;
                            }
                        });
            }
        }
    }

    mUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_USER_SETTINGS_PREFERENCE_KEY);
    mContactSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CONTACT_PREFERENCE_KEYS);
    mPushersSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGETS_PREFERENCE_KEY);
    mPushersSettingsDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGET_DIVIDER_PREFERENCE_KEY);
    mIgnoredUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORED_USERS_PREFERENCE_KEY);
    mIgnoredUserSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORE_USERS_DIVIDER_PREFERENCE_KEY);
    mDevicesListSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_LIST_PREFERENCE_KEY);
    mDevicesListSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_DIVIDER_PREFERENCE_KEY);
    mCryptographyCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_PREFERENCE_KEY);
    mCryptographyCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_DIVIDER_PREFERENCE_KEY);
    mLabsCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_LABS_PREFERENCE_KEY);
    mGroupsFlairCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_GROUPS_FLAIR_KEY);

    // preference to start the App info screen, to facilitate App permissions access
    Preference applicationInfoLInkPref = findPreference(APP_INFO_LINK_PREFERENCE_KEY);
    applicationInfoLInkPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (null != getActivity()) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromParts("package", appContext.getPackageName(), null);
                intent.setData(uri);
                getActivity().getApplicationContext().startActivity(intent);
            }

            return true;
        }
    });

    // Contacts
    setContactsPreferences();

    // user interface preferences
    setUserInterfacePreferences();

    final CheckBoxPreference useCryptoPref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_PREFERENCE_KEY);
    final Preference cryptoIsEnabledPref = findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_IS_ACTIVE_PREFERENCE_KEY);

    cryptoIsEnabledPref.setEnabled(false);

    if (!mSession.isCryptoEnabled()) {
        useCryptoPref.setChecked(false);
        mLabsCategory.removePreference(cryptoIsEnabledPref);
    } else {
        mLabsCategory.removePreference(useCryptoPref);
    }

    useCryptoPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
            if (TextUtils.isEmpty(mSession.getCredentials().deviceId)) {
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.room_settings_labs_end_to_end_warnings)
                        .setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                CommonActivityUtils.logout(getActivity());

                            }
                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).create().show();
            } else {
                boolean newValue = (boolean) newValueAsVoid;

                if (mSession.isCryptoEnabled() != newValue) {
                    displayLoadingView();

                    mSession.enableCrypto(newValue, new ApiCallback<Void>() {
                        private void refresh() {
                            if (null != getActivity()) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        hideLoadingView();
                                        useCryptoPref.setChecked(mSession.isCryptoEnabled());

                                        if (mSession.isCryptoEnabled()) {
                                            mLabsCategory.removePreference(useCryptoPref);
                                            mLabsCategory.addPreference(cryptoIsEnabledPref);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onSuccess(Void info) {
                            useCryptoPref.setEnabled(false);
                            refresh();
                        }

                        @Override
                        public void onNetworkError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onMatrixError(MatrixError e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onUnexpectedError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }
                    });
                }
            }

            return true;
        }
    });

    // SaveMode Managment
    final CheckBoxPreference dataSaveModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_DATA_SAVE_MODE_PREFERENCE_KEY);
    dataSaveModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            List<MXSession> sessions = Matrix.getMXSessions(getActivity());
            for (MXSession session : sessions) {
                session.setUseDataSaveMode((boolean) newValue);
            }

            return true;
        }
    });

    // Analytics tracking managment
    final CheckBoxPreference useAnalyticsModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_ANALYTICS_KEY);

    // On if the analytics tracking is activated
    useAnalyticsModePref.setChecked(PreferencesManager.useAnalytics(appContext));

    useAnalyticsModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseAnalytics(appContext, (boolean) newValue);
            return true;
        }
    });

    // Rageshake Managment
    final CheckBoxPreference useRageShakeModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_RAGE_SHAKE_KEY);
    final boolean mIsUsedRageShake = PreferencesManager.useRageshake(appContext);

    useRageShakeModePref.setChecked(mIsUsedRageShake);

    useRageShakeModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseRageshake(appContext, (boolean) newValue);
            return true;
        }
    });

    // deactivate account
    EditTextPreference deactivateAccountPref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DEACTIVATE_ACCOUNT_KEY);

    if (null != deactivateAccountPref) {
        deactivateAccountPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(DeactivateAccountActivity.Companion.getIntent(getActivity()));

                return false;
            }
        });
    }

    addButtons();
    refreshPushersList();
    refreshEmailsList();
    refreshPhoneNumbersList();
    refreshIgnoredUsersList();
    refreshDevicesList();
    refreshGroupFlairsList();
}

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

private void setPreferences() {
    final android.preference.SwitchPreference MultiServerPreference = (android.preference.SwitchPreference) findPreference(
            "enableMultiServers");
    android.preference.Preference ServerSettings = findPreference("server_settings");
    android.preference.Preference PermissionsSettings = findPreference("permissionssettings");
    android.preference.Preference NotificationLogged = findPreference("notification_show_logs");
    android.preference.Preference fetchServerConfig = findPreference("server_force_fetch_config");
    android.preference.Preference resetApplication = findPreference("reset_settings");
    android.preference.ListPreference displayLanguage = (ListPreference) findPreference("displayLanguage");
    final android.preference.Preference registrationId = findPreference("notification_registration_id");
    android.preference.Preference GeoSettings = findPreference("geo_settings");
    android.preference.SwitchPreference WearPreference = (android.preference.SwitchPreference) findPreference(
            "enableWearItems");
    android.preference.Preference NFCPreference = findPreference("nfc_settings");
    android.preference.Preference QRCodePreference = findPreference("qrcode_settings");
    android.preference.Preference SpeechPreference = findPreference("speech_settings");
    android.preference.SwitchPreference EnableNFCPreference = (android.preference.SwitchPreference) findPreference(
            "enableNFC");
    android.preference.SwitchPreference EnableQRCodePreference = (android.preference.SwitchPreference) findPreference(
            "enableQRCode");
    android.preference.SwitchPreference EnableSpeechPreference = (android.preference.SwitchPreference) findPreference(
            "enableSpeech");
    android.preference.SwitchPreference EnableTalkBackPreference = (android.preference.SwitchPreference) findPreference(
            "talkBack");
    MultiSelectListPreference drawerItems = (MultiSelectListPreference) findPreference("enable_menu_items");
    @SuppressWarnings("SpellCheckingInspection")
    android.preference.SwitchPreference AlwaysOnPreference = (android.preference.SwitchPreference) findPreference(
            "alwayson");
    @SuppressWarnings("SpellCheckingInspection")
    android.preference.PreferenceScreen preferenceScreen = (android.preference.PreferenceScreen) findPreference(
            "settingsscreen");
    android.preference.PreferenceCategory premiumCategory = (android.preference.PreferenceCategory) findPreference(
            "premium_category");
    android.preference.Preference premiumPreference = findPreference("premium_settings");
    NotificationsMultiSelectListPreference notificationsMultiSelectListPreference = (NotificationsMultiSelectListPreference) findPreference(
            "suppressNotifications");
    NotificationsMultiSelectListPreference alarmMultiSelectListPreference = (NotificationsMultiSelectListPreference) findPreference(
            "alarmNotifications");
    android.preference.SwitchPreference ThemePreference = (android.preference.SwitchPreference) findPreference(
            "darkTheme");
    android.preference.Preference FingerPrintSettingsPreference = findPreference("SecuritySettings");
    android.preference.SwitchPreference FingerPrintPreference = (android.preference.SwitchPreference) findPreference(
            "enableSecurity");

    if (!BuildConfig.DEBUG) {
        PreferenceCategory oAndroidAutoCategory = (android.preference.PreferenceCategory) findPreference(
                "androidautocategory");
        PreferenceScreen oNotificationScreen = (android.preference.PreferenceScreen) findPreference(
                "notificationscreen");
        oNotificationScreen.removePreference(oAndroidAutoCategory);
    }//from   ww  w  .j ava  2s  .co  m

    List<String> notifications = mSharedPrefs.getReceivedNotifications();
    if (notifications == null || notifications.size() <= 0) {
        notificationsMultiSelectListPreference.setEnabled(false);
        alarmMultiSelectListPreference.setEnabled(false);
    } else {
        notificationsMultiSelectListPreference.setEnabled(true);
        alarmMultiSelectListPreference.setEnabled(true);
    }

    PermissionsSettings
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    permissionHelper.openSettingsScreen();
                    return true;
                }
            });

    drawerItems.setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
            try {
                final HashSet selectedDrawerItems = (HashSet) newValue;
                if (selectedDrawerItems.size() < 1) {
                    showSnackbar(mContext.getString(R.string.error_atLeastOneItemInDrawer));
                    return false;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
            return true;
        }
    });

    ThemePreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_theme));
                        return false;
                    } else {
                        ((SettingsActivity) getActivity()).reloadSettings();
                        return true;
                    }
                }
            });

    MultiServerPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.multi_server));
                        return false;
                    }
                    return true;
                }
            });

    ServerSettings.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (!MultiServerPreference.isChecked()) {
                Intent intent = new Intent(mContext, ServerSettingsActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(mContext, ServerListSettingsActivity.class);
                startActivity(intent);
            }
            return true;
        }
    });

    FingerPrintSettingsPreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    mContext.startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
                    return true;
                }
            });

    fetchServerConfig
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    UsefulBits.getServerConfigForActiveServer(mContext, true, new ConfigReceiver() {
                        @Override
                        public void onReceiveConfig(ConfigInfo settings) {
                            showSnackbar(mContext.getString(R.string.fetched_server_config_success));
                        }

                        @Override
                        public void onError(Exception error) {
                            showSnackbar(mContext.getString(R.string.fetched_server_config_failed));
                        }
                    }, null);
                    return true;
                }
            });

    displayLanguage
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    showRestartMessage();
                    return true;
                }
            });

    registrationId.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!PermissionsUtil.canAccessDeviceState(mContext)) {
                    permissionHelper.request(PermissionsUtil.INITIAL_DEVICE_PERMS);
                } else {
                    pushGCMRegistrationIds();
                }
            } else {
                pushGCMRegistrationIds();
            }
            return true;
        }
    });

    GeoSettings.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                showPremiumSnackbar(getString(R.string.geofence));
                return false;
            } else {
                Intent intent = new Intent(mContext, GeoSettingsActivity.class);
                startActivity(intent);
                return true;
            }
        }
    });

    EnableNFCPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_nfc));
                        return false;
                    }

                    if (NfcAdapter.getDefaultAdapter(mContext) == null) {
                        showSnackbar(mContext.getString(R.string.nfc_not_supported));
                        return false;
                    }
                    return true;
                }
            });

    EnableQRCodePreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_QRCode));
                        return false;
                    }

                    return true;
                }
            });

    EnableSpeechPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_Speech));
                        return false;
                    }
                    return true;
                }
            });

    EnableTalkBackPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_talk_back));
                        return false;
                    }
                    return true;
                }
            });

    NFCPreference.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(android.preference.Preference preference) {
            if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                showPremiumSnackbar(getString(R.string.category_nfc));
                return false;
            } else {
                Intent intent = new Intent(mContext, NFCSettingsActivity.class);
                startActivity(intent);
                return true;
            }
        }
    });

    QRCodePreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_QRCode));
                        return false;
                    } else {
                        Intent intent = new Intent(mContext, QRCodeSettingsActivity.class);
                        startActivity(intent);
                        return true;
                    }
                }
            });

    SpeechPreference
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_Speech));
                        return false;
                    } else {
                        Intent intent = new Intent(mContext, SpeechSettingsActivity.class);
                        startActivity(intent);
                        return true;
                    }
                }
            });

    WearPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_wear));
                        return false;
                    }
                    return true;
                }
            });

    AlwaysOnPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.always_on_title));
                        return false;
                    }
                    return true;
                }
            });

    NotificationLogged
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    //show dialog
                    List<String> logs = mSharedPrefs.getLoggedNotifications();
                    if (logs != null && logs.size() > 0) {
                        Collections.reverse(logs);
                        new MaterialDialog.Builder(mContext)
                                .title(mContext.getString(R.string.notification_show_title))
                                .items((CharSequence[]) logs.toArray(new String[0])).show();
                    } else
                        UsefulBits.showSimpleToast(mContext, getString(R.string.notification_show_nothing),
                                Toast.LENGTH_LONG);
                    return true;
                }
            });

    //noinspection PointlessBooleanExpression
    if (!BuildConfig.LITE_VERSION) {
        preferenceScreen.removePreference(premiumCategory);
    } else {
        premiumPreference
                .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(android.preference.Preference preference) {
                        String packageID = mContext.getPackageName() + ".premium";
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=" + packageID)));
                        } catch (android.content.ActivityNotFoundException ignored) {
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("https://play.google.com/store/apps/details?id=" + packageID)));
                        }

                        return true;
                    }
                });
    }

    resetApplication
            .setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(android.preference.Preference preference) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        new MaterialDialog.Builder(mContext).title(R.string.category_Reset)
                                .content(R.string.are_you_sure).positiveText(R.string.ok)
                                .negativeText(R.string.cancel)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @SuppressLint("NewApi")
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog,
                                            @NonNull DialogAction which) {
                                        ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE))
                                                .clearApplicationUserData();
                                    }
                                }).show();
                    } else {
                        startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                    }
                    return true;
                }
            });

    FingerPrintPreference
            .setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
                @SuppressLint("NewApi")
                @Override
                public boolean onPreferenceChange(android.preference.Preference preference, Object o) {
                    if (mSharedPrefs.isStartupSecurityEnabled())
                        return true;
                    if (BuildConfig.LITE_VERSION || !mSharedPrefs.isAPKValidated()) {
                        showPremiumSnackbar(getString(R.string.category_startup_security));
                        return false;
                    } else {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                            UsefulBits.showSimpleToast(mContext, getString(R.string.fingerprint_not_supported),
                                    Toast.LENGTH_LONG);
                            return false;
                        }
                        if (!PermissionsUtil.canAccessFingerprint(mContext)) {
                            permissionHelper.request(PermissionsUtil.INITIAL_FINGERPRINT_PERMS);
                        } else {
                            FingerprintManager fingerprintManager = (FingerprintManager) mContext
                                    .getSystemService(Context.FINGERPRINT_SERVICE);
                            if (ActivityCompat.checkSelfPermission(mContext,
                                    Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                                return false;
                            }
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if (!fingerprintManager.isHardwareDetected()) {
                                    return false;
                                } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                                    UsefulBits.showSimpleToast(mContext,
                                            getString(R.string.fingerprint_not_setup_in_android),
                                            Toast.LENGTH_LONG);
                                    return false;
                                } else {
                                    new MaterialDialog.Builder(mContext)
                                            .title(R.string.category_startup_security)
                                            .content(R.string.fingerprint_sure).positiveText(R.string.ok)
                                            .negativeText(R.string.cancel)
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog,
                                                        @NonNull DialogAction which) {
                                                    mSharedPrefs.setStartupSecurityEnabled(true);
                                                    ((SettingsActivity) getActivity()).reloadSettings();
                                                }
                                            }).show();

                                    return false;
                                }
                            }
                        }
                    }
                    return false;
                }
            });
}