Example usage for android.preference EditTextPreference setOnPreferenceChangeListener

List of usage examples for android.preference EditTextPreference setOnPreferenceChangeListener

Introduction

In this page you can find the example usage for android.preference EditTextPreference 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:org.thoughtcrime.securesms.MmsPreferencesFragment.java

private void initializeEditTextSummary(final EditTextPreference preference) {
    if (preference.getText() == null) {
        preference.setSummary("Not set");
    } else {//from   w w  w .  ja  v  a2  s  .  c  om
        preference.setSummary(preference.getText());
    }

    preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference pref, Object newValue) {
            preference.setSummary(newValue == null ? "Not set" : ((String) newValue));
            return true;
        }
    });
}

From source file:org.deviceconnect.android.client.fragment.AbstractSettingsFragment.java

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

    Bundle args = new Bundle();
    args.putParcelableArrayList(OpenSourceLicenseFragment.EXTRA_OSS, getOpenSourceSoftware());
    mOssFragment = new OpenSourceLicenseFragment();
    mOssFragment.setArguments(args);/*  w  w  w.jav  a2  s  .  c  o  m*/

    Bundle policyArgs = new Bundle();
    policyArgs.putInt(Intent.EXTRA_TITLE, R.string.privacy_policy);
    policyArgs.putInt(Intent.EXTRA_TEXT, R.raw.privacypolicy);
    mPrivacyPolicyFragment = new TextDialogFragment();
    mPrivacyPolicyFragment.setArguments(policyArgs);

    Bundle tosArgs = new Bundle();
    tosArgs.putInt(Intent.EXTRA_TITLE, R.string.terms_of_service);
    tosArgs.putInt(Intent.EXTRA_TEXT, R.raw.termsofservice);
    mTermsOfServiceFragment = new TextDialogFragment();
    mTermsOfServiceFragment.setArguments(tosArgs);

    PreferenceScreen versionPreferences = (PreferenceScreen) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_about_appinfo));
    try {
        versionPreferences.setSummary((getActivity().getPackageManager()
                .getPackageInfo(getActivity().getPackageName(), 0).versionName));
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    CheckBoxPreference checkBoxSslPreferences = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_ssl));
    checkBoxSslPreferences.setOnPreferenceChangeListener(this);

    EditTextPreference editHostPreferences = (EditTextPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_host));
    editHostPreferences.setOnPreferenceChangeListener(this);
    editHostPreferences.setSummary(editHostPreferences.getText());

    EditTextPreference editPortPreferences = (EditTextPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_port));
    editPortPreferences.setOnPreferenceChangeListener(this);
    editPortPreferences.setSummary(editPortPreferences.getText());

    // Local OAuth
    SettingsActivity activity = (SettingsActivity) getActivity();

    EditTextPreference editClientIdPreferences = (EditTextPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_client_id));
    editClientIdPreferences.setSummary(activity.getClientId());

    EditTextPreference editClientSecretPreferences = (EditTextPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_client_secret));
    editClientSecretPreferences.setSummary(activity.getClientSecret());

    EditTextPreference editAccessTokenPreferences = (EditTextPreference) getPreferenceScreen()
            .findPreference(getString(R.string.key_settings_dconn_access_token));
    editAccessTokenPreferences.setSummary(activity.getAccessToken());
}

From source file:com.tinfoil.sms.settings.QuickPrefsActivity.java

/**
 * Things done when the preference menu is created  
 * Left as default/*from  ww w.j  a  v a  2s  .com*/
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setupActionBar();
    /*
     * Add preferences from the options.xml file.
     */
    addPreferencesFromResource(R.xml.options);

    setKitKatPref();

    PreferenceScreen sourceCode = (PreferenceScreen) findPreference(SOURCE_CODE_SETTING_KEY);
    sourceCode.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(QuickPrefsActivity.this.getString(R.string.tinfoil_sms_github)));
            QuickPrefsActivity.this.startActivity(i);

            return true;
        }

    });

    EditTextPreference vibrateLength = (EditTextPreference) findPreference(VIBRATE_LENGTH_SETTING_KEY);
    vibrateLength.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean ret = false;

            try {
                if (SMSUtility.isASmallNumber(newValue.toString())
                        && Integer.valueOf(newValue.toString()) > 0) {
                    ret = true;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return ret;
        }

    });

    //TODO implement the OnPreferenceChangeListener for the other preferences that use numbers only
    EditTextPreference messageLimit = (EditTextPreference) findPreference(MESSAGE_LIMIT_SETTING_KEY);
    messageLimit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean ret = false;

            try {
                if (SMSUtility.isASmallNumber(newValue.toString())
                        && Integer.valueOf(newValue.toString()) > 0) {
                    ret = true;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return ret;
        }
    });

    findPreference("enable_walkthrough").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // If walkthrough enabled, reset all the steps so they are displayed again
            if (Boolean.valueOf(newValue.toString())) {
                Walkthrough.enableWalkthrough(QuickPrefsActivity.this);
            } else {
                Walkthrough.disableWalkthrough(QuickPrefsActivity.this);
            }
            return true;
        }
    });

    /* Set an onclick listener for contact developers */
    findPreference("contact").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            /**
             * Create the Intent
             */
            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

            /**
             * Fill it with Data
             */
            emailIntent.setType("plain/text");
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                    QuickPrefsActivity.this.getResources().getStringArray(R.array.dev_emails));
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                    getResources().getString(R.string.email_subject));
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");

            /**
             * Send it off to the Activity-Chooser
             */
            QuickPrefsActivity.this.startActivity(Intent.createChooser(emailIntent,
                    QuickPrefsActivity.this.getResources().getString(R.string.email_chooser)));
            return true;
        }
    });
}

From source file:fr.free.nrw.commons.settings.SettingsFragment.java

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

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    // Update spinner to show selected value as summary
    ListPreference licensePreference = (ListPreference) findPreference(Prefs.DEFAULT_LICENSE);
    licensePreference.setSummary(getString(Utils.licenseNameFor(licensePreference.getValue())));

    // Keep summary updated when changing value
    licensePreference.setOnPreferenceChangeListener((preference, newValue) -> {
        preference.setSummary(getString(Utils.licenseNameFor((String) newValue)));
        return true;
    });/* w w  w  .j av a2 s.c  om*/

    CheckBoxPreference themePreference = (CheckBoxPreference) findPreference("theme");
    themePreference.setOnPreferenceChangeListener((preference, newValue) -> {
        getActivity().recreate();
        return true;
    });

    final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads");
    int uploads = prefs.getInt(Prefs.UPLOADS_SHOWING, 100);
    uploadLimit.setText(uploads + "");
    uploadLimit.setSummary(uploads + "");
    uploadLimit.setOnPreferenceChangeListener((preference, newValue) -> {
        int value = Integer.parseInt(newValue.toString());
        final SharedPreferences.Editor editor = prefs.edit();
        if (value > 500) {
            new AlertDialog.Builder(getActivity()).setTitle(R.string.maximum_limit)
                    .setMessage(R.string.maximum_limit_alert)
                    .setPositiveButton(android.R.string.yes, (dialog, which) -> {
                    }).setIcon(android.R.drawable.ic_dialog_alert).show();
            editor.putInt(Prefs.UPLOADS_SHOWING, 500);
            editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, true);
            uploadLimit.setSummary(500 + "");
            uploadLimit.setText(500 + "");
        } else {
            editor.putInt(Prefs.UPLOADS_SHOWING, Integer.parseInt(newValue.toString()));
            editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, true);
            uploadLimit.setSummary(newValue.toString());
        }
        editor.apply();
        return true;
    });

    Preference sendLogsPreference = findPreference("sendLogFile");
    sendLogsPreference.setOnPreferenceClickListener(preference -> {
        //first we need to check if we have the necessary permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                sendAppLogsViaEmail();
            } else {
                //first get the necessary permission
                requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                        REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            }
        } else {
            sendAppLogsViaEmail();
        }

        return true;
    });
}

From source file:nya.miku.wishmaster.chans.endchan.EndChanModule.java

private void addDomainPreferences(PreferenceGroup group) {
    Context context = group.getContext();
    Preference.OnPreferenceChangeListener updateDomainListener = new Preference.OnPreferenceChangeListener() {
        @Override/*from   w  w  w.  j  a v a2 s  .  c om*/
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals(getSharedKey(PREF_KEY_DOMAIN))) {
                updateDomain((String) newValue);
                return true;
            }
            return false;
        }
    };
    PreferenceCategory domainCat = new PreferenceCategory(context);
    domainCat.setTitle(R.string.makaba_prefs_domain_category);
    group.addPreference(domainCat);
    EditTextPreference domainPref = new EditTextPreference(context);
    domainPref.setTitle(R.string.pref_domain);
    domainPref.setDialogTitle(R.string.pref_domain);
    domainPref.setSummary(resources.getString(R.string.pref_domain_summary, DOMAINS_HINT));
    domainPref.setKey(getSharedKey(PREF_KEY_DOMAIN));
    domainPref.getEditText().setHint(DEFAULT_DOMAIN);
    domainPref.getEditText().setSingleLine();
    domainPref.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
    domainPref.setOnPreferenceChangeListener(updateDomainListener);
    domainCat.addPreference(domainPref);
}

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  ww.j a v a 2  s . co  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.ichi2.anki.PreferenceContext.java

private void initSubscreen(String action, PreferenceContext listener) {
    PreferenceScreen screen;//from   w  w  w .  ja va  2  s.  c  o m
    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:net.freifunk.android.discover.SettingsActivity.java

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

    addPreferencesFromResource(R.xml.pref_data_sync);

    // get data via the key
    ArrayList<NodeMap> nodeMapArrayList = new ArrayList<NodeMap>(MapMaster.getInstance().getMaps().values());
    PreferenceCategory communities = (PreferenceCategory) findPreference("communities");

    // sort by Name
    Collections.sort(nodeMapArrayList, new NodeMapComparator());

    if (nodeMapArrayList != null && communities != null) {
        for (final NodeMap nm : nodeMapArrayList) {

            PreferenceScreen communityPreferenceScreen = getPreferenceManager()
                    .createPreferenceScreen(SettingsActivity.this);

            communityPreferenceScreen.setTitle(nm.getMapName());
            communityPreferenceScreen.setKey(nm.getMapName());

            final CheckBoxPreference deactivateCommunityPreference = new CheckBoxPreference(
                    SettingsActivity.this);

            // TODO: move Strings to resources
            deactivateCommunityPreference.setTitle("Community aktiv");
            deactivateCommunityPreference
                    .setSummary("deaktivieren, falls Community nicht auf der Karte angezeigt werden soll");
            deactivateCommunityPreference.setKey("community_deactivate_" + nm.getMapName());
            deactivateCommunityPreference.setChecked(nm.isActive());
            deactivateCommunityPreference
                    .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                        @Override
                        public boolean onPreferenceChange(Preference preference, Object newValue) {

                            Database db = Database.getInstance(null);

                            boolean newActive = newValue.toString().equals("true") ? true : false;

                            nm.setActive(newActive);
                            db.addNodeMap(nm);

                            // reload if set to active
                            if (newActive) {
                                nm.loadNodes();
                            } else {
                                nm.updateNodes();
                            }/* ww w  .  j  a  v a  2 s  .com*/

                            return true;
                        }
                    });

            EditTextPreference editCommunityPreference = new EditTextPreference(SettingsActivity.this);

            // TODO: move Strings to resources
            editCommunityPreference.setTitle("URL bearbeiten");
            editCommunityPreference.setSummary("aendern, falls eine andere Quelle genutzt werden soll.");
            editCommunityPreference.setKey("community_edit_" + nm.getMapName());
            editCommunityPreference.setText(nm.getMapUrl());

            editCommunityPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {

                    Database db = Database.getInstance(null);

                    // remove old nodes from map
                    nm.setActive(false);
                    EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_NODES, nm));

                    // we should probably do this async as well
                    db.deleteAllNodesForMap(nm);

                    // load new nodes
                    NodeMap newMap = new NodeMap(nm.getMapName(), (String) newValue, true);
                    db.addNodeMap(newMap);

                    //HashMap<String, NodeMap> nodeResult = new HashMap<String, NodeMap>(1);
                    //nodeResult.put(nm.getMapName(), nm);

                    newMap.updateNodes();
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.LOAD_NODES, nm));
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_MAP, nodeResult));

                    return true;
                }
            });

            communityPreferenceScreen.addPreference(deactivateCommunityPreference);
            communityPreferenceScreen.addPreference(editCommunityPreference);

            communities.addPreference(communityPreferenceScreen);
        }
    }

    setupActionBar();

}

From source file:org.linphone.AccountPreferencesFragment.java

private void initAccountPreferencesFields(PreferenceScreen parent) {
    boolean isDefaultAccount = mPrefs.getDefaultAccountIndex() == n;

    accountCreator = LinphoneCoreFactory.instance().createAccountCreator(LinphoneManager.getLc(),
            LinphonePreferences.instance().getXmlrpcUrl());
    accountCreator.setListener(this);

    PreferenceCategory account = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_sipaccount_key));
    EditTextPreference username = (EditTextPreference) account.getPreference(0);
    username.setOnPreferenceChangeListener(usernameChangedListener);
    if (!isNewAccount) {
        username.setText(mPrefs.getAccountUsername(n));
        username.setSummary(username.getText());
    }/*from  w w w.  j a v  a  2s  .  c o  m*/

    EditTextPreference userid = (EditTextPreference) account.getPreference(1);
    userid.setOnPreferenceChangeListener(useridChangedListener);
    if (!isNewAccount) {
        userid.setText(mPrefs.getAccountUserId(n));
        userid.setSummary(userid.getText());
    }

    EditTextPreference password = (EditTextPreference) account.getPreference(2);
    password.setOnPreferenceChangeListener(passwordChangedListener);
    if (!isNewAccount) {
        password.setText(mPrefs.getAccountPassword(n));
    }

    EditTextPreference domain = (EditTextPreference) account.getPreference(3);
    domain.setOnPreferenceChangeListener(domainChangedListener);
    if (!isNewAccount) {
        domain.setText(mPrefs.getAccountDomain(n));
        domain.setSummary(domain.getText());
    }

    EditTextPreference displayName = (EditTextPreference) account.getPreference(4);
    displayName.setOnPreferenceChangeListener(displayNameChangedListener);
    if (!isNewAccount) {
        displayName.setText(mPrefs.getAccountDisplayName(n));
        displayName.setSummary(displayName.getText());
    }

    PreferenceCategory advanced = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_advanced_key));
    mTransportPreference = (ListPreference) advanced.getPreference(0);
    initializeTransportPreference(mTransportPreference);
    mTransportPreference.setOnPreferenceChangeListener(transportChangedListener);
    if (!isNewAccount) {
        mTransportPreference.setSummary(mPrefs.getAccountTransportString(n));
    }

    mProxyPreference = (EditTextPreference) advanced.getPreference(1);
    mProxyPreference.setOnPreferenceChangeListener(proxyChangedListener);
    if (!isNewAccount) {
        mProxyPreference.setText(mPrefs.getAccountProxy(n));
        mProxyPreference
                .setSummary("".equals(mProxyPreference.getText()) || (mProxyPreference.getText() == null)
                        ? getString(R.string.pref_help_proxy)
                        : mProxyPreference.getText());
    }

    CheckBoxPreference outboundProxy = (CheckBoxPreference) advanced.getPreference(2);
    outboundProxy.setOnPreferenceChangeListener(outboundProxyChangedListener);
    if (!isNewAccount) {
        outboundProxy.setChecked(mPrefs.isAccountOutboundProxySet(n));
    }

    EditTextPreference expires = (EditTextPreference) advanced.getPreference(3);
    expires.setOnPreferenceChangeListener(expiresChangedListener);
    if (!isNewAccount) {
        expires.setText(mPrefs.getExpires(n));
        expires.setSummary(mPrefs.getExpires(n));
    }

    EditTextPreference prefix = (EditTextPreference) advanced.getPreference(4);
    prefix.setOnPreferenceChangeListener(prefixChangedListener);
    if (!isNewAccount) {
        String prefixValue = mPrefs.getPrefix(n);
        prefix.setText(prefixValue);
        prefix.setSummary(prefixValue);
    }

    CheckBoxPreference avpf = (CheckBoxPreference) advanced.getPreference(5);
    avpf.setOnPreferenceChangeListener(avpfChangedListener);
    if (!isNewAccount) {
        avpf.setChecked(mPrefs.avpfEnabled(n));
    }

    EditTextPreference avpfRRInterval = (EditTextPreference) advanced.getPreference(6);
    avpfRRInterval.setOnPreferenceChangeListener(avpfRRIntervalChangedListener);
    if (!isNewAccount) {
        avpfRRInterval.setText(mPrefs.getAvpfRRInterval(n));
        avpfRRInterval.setSummary(mPrefs.getAvpfRRInterval(n));
    }

    CheckBoxPreference escape = (CheckBoxPreference) advanced.getPreference(7);
    escape.setOnPreferenceChangeListener(escapeChangedListener);
    if (!isNewAccount) {
        escape.setChecked(mPrefs.getReplacePlusByZeroZero(n));
    }

    Preference linkAccount = advanced.getPreference(8);
    linkAccount.setOnPreferenceClickListener(linkAccountListener);

    PreferenceCategory manage = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_manage_key));
    final CheckBoxPreference disable = (CheckBoxPreference) manage.getPreference(0);
    disable.setEnabled(true);
    disable.setOnPreferenceChangeListener(disableChangedListener);
    if (!isNewAccount) {
        disable.setChecked(!mPrefs.isAccountEnabled(n));
    }

    CheckBoxPreference mainAccount = (CheckBoxPreference) manage.getPreference(1);
    mainAccount.setChecked(isDefaultAccount);
    mainAccount.setEnabled(!mainAccount.isChecked());
    mainAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            mPrefs.setDefaultAccount(n);
            disable.setEnabled(false);
            disable.setChecked(false);
            preference.setEnabled(false);
            return true;
        }
    });
    if (!isNewAccount) {
        mainAccount.setEnabled(!mainAccount.isChecked());
    }

    final Preference changePassword = manage.getPreference(2);
    if (mPrefs.getAccountDomain(n).compareTo(getString(R.string.default_domain)) == 0) {
        changePassword.setEnabled(!isNewAccount);
        changePassword.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                final AlertDialog.Builder alert = new AlertDialog.Builder(LinphoneActivity.instance());
                LayoutInflater inflater = LinphoneActivity.instance().getLayoutInflater();
                View layout = inflater.inflate(R.layout.new_password, null);
                final EditText pass1 = (EditText) layout.findViewById(R.id.password1);
                final EditText pass2 = (EditText) layout.findViewById(R.id.password2);
                alert.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LinphoneAccountCreator.PasswordCheck status = accountCreator
                                .setPassword(pass1.getText().toString());
                        if (status.equals(LinphoneAccountCreator.PasswordCheck.Ok)) {
                            if (pass1.getText().toString().compareTo(pass2.getText().toString()) == 0) {
                                accountCreator.setUsername(mPrefs.getAccountUsername(n));
                                accountCreator.setHa1(mPrefs.getAccountHa1(n));
                                LinphoneAccountCreator.RequestStatus req_status = accountCreator
                                        .updatePassword(pass1.getText().toString());
                                if (!req_status.equals(LinphoneAccountCreator.RequestStatus.Ok)) {
                                    LinphoneUtils.displayErrorAlert(
                                            LinphoneUtils.errorForRequestStatus(req_status),
                                            LinphoneActivity.instance());
                                } else {
                                    progress = ProgressDialog.show(LinphoneActivity.instance(), null, null);
                                    Drawable d = new ColorDrawable(ContextCompat
                                            .getColor(LinphoneActivity.instance(), R.color.colorE));
                                    d.setAlpha(200);
                                    progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                                            WindowManager.LayoutParams.MATCH_PARENT);
                                    progress.getWindow().setBackgroundDrawable(d);
                                    progress.setContentView(R.layout.progress_dialog);
                                    progress.show();
                                }
                            } else {
                                LinphoneUtils.displayErrorAlert(getString(R.string.wizard_passwords_unmatched),
                                        LinphoneActivity.instance());
                            }
                            return;
                        }
                        LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPasswordStatus(status),
                                LinphoneActivity.instance());
                    }
                });

                alert.setView(layout);
                alert.show();
                return true;
            }
        });
    } else {
        changePassword.setEnabled(false);
    }

    final Preference delete = manage.getPreference(3);
    delete.setEnabled(!isNewAccount);
    delete.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            mPrefs.deleteAccount(n);
            LinphoneActivity.instance().refreshAccounts();
            LinphoneActivity.instance().displaySettings();
            return true;
        }
    });
}

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

private void initAccountPreferencesFields(PreferenceScreen parent) {
    boolean isDefaultAccount = mPrefs.getDefaultAccountIndex() == n;

    accountCreator = LinphoneCoreFactory.instance().createAccountCreator(LinphoneManager.getLc(),
            LinphonePreferences.instance().getXmlrpcUrl());
    accountCreator.setListener(this);

    PreferenceCategory account = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_sipaccount_key));
    EditTextPreference username = (EditTextPreference) account.getPreference(0);
    username.setOnPreferenceChangeListener(usernameChangedListener);
    if (!isNewAccount) {
        username.setText(mPrefs.getAccountUsername(n));
        username.setSummary(username.getText());
    }/*from  ww  w. j  a v  a 2  s.  c o  m*/

    EditTextPreference userid = (EditTextPreference) account.getPreference(1);
    userid.setOnPreferenceChangeListener(useridChangedListener);
    if (!isNewAccount) {
        userid.setText(mPrefs.getAccountUserId(n));
        userid.setSummary(userid.getText());
    }

    EditTextPreference password = (EditTextPreference) account.getPreference(2);
    password.setOnPreferenceChangeListener(passwordChangedListener);
    if (!isNewAccount) {
        password.setText(mPrefs.getAccountPassword(n));
    }

    EditTextPreference domain = (EditTextPreference) account.getPreference(3);
    domain.setOnPreferenceChangeListener(domainChangedListener);
    if (!isNewAccount) {
        domain.setText(mPrefs.getAccountDomain(n));
        domain.setSummary(domain.getText());
    }

    EditTextPreference displayName = (EditTextPreference) account.getPreference(4);
    displayName.setOnPreferenceChangeListener(displayNameChangedListener);
    if (!isNewAccount) {
        displayName.setText(mPrefs.getAccountDisplayName(n));
        displayName.setSummary(displayName.getText());
    }

    PreferenceCategory advanced = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_advanced_key));
    mTransportPreference = (ListPreference) advanced.getPreference(0);
    initializeTransportPreference(mTransportPreference);
    mTransportPreference.setOnPreferenceChangeListener(transportChangedListener);
    if (!isNewAccount) {
        mTransportPreference.setSummary(mPrefs.getAccountTransportString(n));
    }

    mProxyPreference = (EditTextPreference) advanced.getPreference(1);
    mProxyPreference.setOnPreferenceChangeListener(proxyChangedListener);
    if (!isNewAccount) {
        mProxyPreference.setText(mPrefs.getAccountProxy(n));
        mProxyPreference
                .setSummary("".equals(mProxyPreference.getText()) || (mProxyPreference.getText() == null)
                        ? getString(R.string.pref_help_proxy)
                        : mProxyPreference.getText());
    }

    CheckBoxPreference outboundProxy = (CheckBoxPreference) advanced.getPreference(2);
    outboundProxy.setOnPreferenceChangeListener(outboundProxyChangedListener);
    if (!isNewAccount) {
        outboundProxy.setChecked(mPrefs.isAccountOutboundProxySet(n));
    }

    EditTextPreference expires = (EditTextPreference) advanced.getPreference(3);
    expires.setOnPreferenceChangeListener(expiresChangedListener);
    if (!isNewAccount) {
        expires.setText(mPrefs.getExpires(n));
        expires.setSummary(mPrefs.getExpires(n));
    }

    EditTextPreference prefix = (EditTextPreference) advanced.getPreference(4);
    prefix.setOnPreferenceChangeListener(prefixChangedListener);
    if (!isNewAccount) {
        String prefixValue = mPrefs.getPrefix(n);
        prefix.setText(prefixValue);
        prefix.setSummary(prefixValue);
    }

    CheckBoxPreference avpf = (CheckBoxPreference) advanced.getPreference(5);
    avpf.setOnPreferenceChangeListener(avpfChangedListener);
    if (!isNewAccount) {
        avpf.setChecked(mPrefs.avpfEnabled(n));
    }

    EditTextPreference avpfRRInterval = (EditTextPreference) advanced.getPreference(6);
    avpfRRInterval.setOnPreferenceChangeListener(avpfRRIntervalChangedListener);
    if (!isNewAccount) {
        avpfRRInterval.setText(mPrefs.getAvpfRRInterval(n));
        avpfRRInterval.setSummary(mPrefs.getAvpfRRInterval(n));
    }

    CheckBoxPreference escape = (CheckBoxPreference) advanced.getPreference(7);
    escape.setOnPreferenceChangeListener(escapeChangedListener);
    if (!isNewAccount) {
        escape.setChecked(mPrefs.getReplacePlusByZeroZero(n));
    }

    CheckBoxPreference friendlistSubscribe = (CheckBoxPreference) advanced.getPreference(8);
    friendlistSubscribe.setOnPreferenceChangeListener(friendlistSubscribeListener);
    if (!isNewAccount) {
        friendlistSubscribe.setChecked(mPrefs.isFriendlistsubscriptionEnabled());
    }

    Preference linkAccount = advanced.getPreference(9);
    linkAccount.setOnPreferenceClickListener(linkAccountListener);

    PreferenceCategory manage = (PreferenceCategory) getPreferenceScreen()
            .findPreference(getString(R.string.pref_manage_key));
    final CheckBoxPreference disable = (CheckBoxPreference) manage.getPreference(0);
    disable.setEnabled(true);
    disable.setOnPreferenceChangeListener(disableChangedListener);
    if (!isNewAccount) {
        disable.setChecked(!mPrefs.isAccountEnabled(n));
    }

    CheckBoxPreference mainAccount = (CheckBoxPreference) manage.getPreference(1);
    mainAccount.setChecked(isDefaultAccount);
    mainAccount.setEnabled(!mainAccount.isChecked());
    mainAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            mPrefs.setDefaultAccount(n);
            disable.setEnabled(false);
            disable.setChecked(false);
            preference.setEnabled(false);
            return true;
        }
    });
    if (!isNewAccount) {
        mainAccount.setEnabled(!mainAccount.isChecked());
    }

    final Preference changePassword = manage.getPreference(2);
    if (mPrefs.getAccountDomain(n).compareTo(getString(R.string.default_domain)) == 0) {
        changePassword.setEnabled(!isNewAccount);
        changePassword.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                final AlertDialog.Builder alert = new AlertDialog.Builder(LinphoneActivity.instance());
                LayoutInflater inflater = LinphoneActivity.instance().getLayoutInflater();
                View layout = inflater.inflate(R.layout.new_password, null);
                final EditText pass1 = (EditText) layout.findViewById(R.id.password1);
                final EditText pass2 = (EditText) layout.findViewById(R.id.password2);
                alert.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LinphoneAccountCreator.Status status = accountCreator
                                .setPassword(pass1.getText().toString());
                        if (status.equals(LinphoneAccountCreator.Status.Ok)) {
                            if (pass1.getText().toString().compareTo(pass2.getText().toString()) == 0) {
                                accountCreator.setUsername(mPrefs.getAccountUsername(n));
                                accountCreator.setHa1(mPrefs.getAccountHa1(n));
                                status = accountCreator.updatePassword(pass1.getText().toString());
                                if (!status.equals(LinphoneAccountCreator.Status.Ok)) {
                                    LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status),
                                            LinphoneActivity.instance());
                                } else {
                                    progress = ProgressDialog.show(LinphoneActivity.instance(), null, null);
                                    Drawable d = new ColorDrawable(ContextCompat
                                            .getColor(LinphoneActivity.instance(), R.color.colorE));
                                    d.setAlpha(200);
                                    progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                                            WindowManager.LayoutParams.MATCH_PARENT);
                                    progress.getWindow().setBackgroundDrawable(d);
                                    progress.setContentView(R.layout.progress_dialog);
                                    progress.show();
                                }
                            } else {
                                LinphoneUtils.displayErrorAlert(getString(R.string.wizard_passwords_unmatched),
                                        LinphoneActivity.instance());
                            }
                            return;
                        }
                        LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status),
                                LinphoneActivity.instance());
                    }
                });

                alert.setView(layout);
                alert.show();
                return true;
            }
        });
    } else {
        changePassword.setEnabled(false);
    }

    final Preference delete = manage.getPreference(3);
    delete.setEnabled(!isNewAccount);
    delete.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            mPrefs.deleteAccount(n);
            LinphoneActivity.instance().refreshAccounts();
            LinphoneActivity.instance().displaySettings();
            return true;
        }
    });
}