Example usage for android.preference EditTextPreference getEditText

List of usage examples for android.preference EditTextPreference getEditText

Introduction

In this page you can find the example usage for android.preference EditTextPreference getEditText.

Prototype

public EditText getEditText() 

Source Link

Document

Returns the EditText widget that will be shown in the dialog.

Usage

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

private void addDomainPreferences(PreferenceGroup group) {
    Context context = group.getContext();
    Preference.OnPreferenceChangeListener updateDomainListener = new Preference.OnPreferenceChangeListener() {
        @Override//from   w w w.  j a  va 2s .  c om
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals(getSharedKey(PREF_KEY_DOMAIN))) {
                domain = (String) newValue;
                if (domain.length() == 0)
                    domain = DEFAULT_DOMAIN;
                loadHanabiraCookie();
                return true;
            }
            return false;
        }
    };
    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);
    group.addPreference(domainPref);
}

From source file:com.nttec.everychan.chans.makaba.MakabaModule.java

/**   ?  ( .. https) */
private void addDomainPreferences(PreferenceGroup group) {
    Context context = group.getContext();
    Preference.OnPreferenceChangeListener updateDomainListener = new Preference.OnPreferenceChangeListener() {
        @Override/*from   ww w  . j a  v a  2s.  c o  m*/
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals(getSharedKey(PREF_KEY_DOMAIN))) {
                updateDomain((String) newValue,
                        preferences.getBoolean(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA), true));
                return true;
            } else if (preference.getKey().equals(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA))) {
                updateDomain(preferences.getString(getSharedKey(PREF_KEY_DOMAIN), DEFAULT_DOMAIN),
                        (boolean) 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);
    CheckBoxPreference httpsPref = new LazyPreferences.CheckBoxPreference(context); //? "? https"
    httpsPref.setTitle(R.string.pref_use_https);
    httpsPref.setSummary(R.string.pref_use_https_summary);
    httpsPref.setKey(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA));
    httpsPref.setDefaultValue(true);
    httpsPref.setOnPreferenceChangeListener(updateDomainListener);
    domainCat.addPreference(httpsPref);
}

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

private void updateView() {

    // user id//from   w w w  .  j a  v  a  2 s. co m
    EditTextPreference uidEditTextPref = (EditTextPreference) findPreference("uidpref");
    uidEditTextPref.setText(manetcfg.getUserId());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // battery temperature

    setupFlag = true;
}

From source file:github.popeen.dsub.fragments.SettingsFragment.java

private PreferenceScreen expandServer(final int instance) {
    final PreferenceScreen screen = this.getPreferenceManager().createPreferenceScreen(context);
    screen.setTitle(R.string.settings_server_unused);
    screen.setKey(Constants.PREFERENCES_KEY_SERVER_KEY + instance);

    final EditTextPreference serverNamePreference = new EditTextPreference(context);
    serverNamePreference.setKey(Constants.PREFERENCES_KEY_SERVER_NAME + instance);
    serverNamePreference.setDefaultValue(getResources().getString(R.string.settings_server_unused));
    serverNamePreference.setTitle(R.string.settings_server_name);
    serverNamePreference.setDialogTitle(R.string.settings_server_name);

    if (serverNamePreference.getText() == null) {
        serverNamePreference.setText(getResources().getString(R.string.settings_server_unused));
    }//  w  w  w  .  ja va 2  s . com

    serverNamePreference.setSummary(serverNamePreference.getText());

    final EditTextPreference serverUrlPreference = new EditTextPreference(context);
    serverUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_URL + instance);
    serverUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverUrlPreference.setDefaultValue("http://yourhost");
    serverUrlPreference.setTitle(R.string.settings_server_address);
    serverUrlPreference.setDialogTitle(R.string.settings_server_address);

    if (serverUrlPreference.getText() == null) {
        serverUrlPreference.setText("http://yourhost");
    }

    serverUrlPreference.setSummary(serverUrlPreference.getText());
    screen.setSummary(serverUrlPreference.getText());

    final EditTextPreference serverLocalNetworkSSIDPreference = new EditTextPreference(context) {
        @Override
        protected void onAddEditTextToDialogView(View dialogView, final EditText editText) {
            super.onAddEditTextToDialogView(dialogView, editText);
            ViewGroup root = (ViewGroup) ((ViewGroup) dialogView).getChildAt(0);

            Button defaultButton = new Button(getContext());
            defaultButton.setText(internalSSIDDisplay);
            defaultButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editText.setText(internalSSID);
                }
            });
            root.addView(defaultButton);
        }
    };
    serverLocalNetworkSSIDPreference.setKey(Constants.PREFERENCES_KEY_SERVER_LOCAL_NETWORK_SSID + instance);
    serverLocalNetworkSSIDPreference.setTitle(R.string.settings_server_local_network_ssid);
    serverLocalNetworkSSIDPreference.setDialogTitle(R.string.settings_server_local_network_ssid);

    final EditTextPreference serverInternalUrlPreference = new EditTextPreference(context);
    serverInternalUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance);
    serverInternalUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverInternalUrlPreference.setDefaultValue("");
    serverInternalUrlPreference.setTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setDialogTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setSummary(serverInternalUrlPreference.getText());

    final EditTextPreference serverUsernamePreference = new EditTextPreference(context);
    serverUsernamePreference.setKey(Constants.PREFERENCES_KEY_USERNAME + instance);
    serverUsernamePreference.setTitle(R.string.settings_server_username);
    serverUsernamePreference.setDialogTitle(R.string.settings_server_username);

    final EditTextPreference serverPasswordPreference = new EditTextPreference(context);
    serverPasswordPreference.setKey(Constants.PREFERENCES_KEY_PASSWORD + instance);
    serverPasswordPreference.getEditText()
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    serverPasswordPreference.setSummary("***");
    serverPasswordPreference.setTitle(R.string.settings_server_password);
    final CheckBoxPreference serverSyncPreference = new CheckBoxPreference(context);
    serverSyncPreference.setKey(Constants.PREFERENCES_KEY_SERVER_SYNC + instance);
    serverSyncPreference.setChecked(Util.isSyncEnabled(context, instance));
    serverSyncPreference.setSummary(R.string.settings_server_sync_summary);
    serverSyncPreference.setTitle(R.string.settings_server_sync);

    final Preference serverOpenBrowser = new Preference(context);
    serverOpenBrowser.setKey(Constants.PREFERENCES_KEY_OPEN_BROWSER);
    serverOpenBrowser.setPersistent(false);
    serverOpenBrowser.setTitle(R.string.settings_server_open_browser);
    serverOpenBrowser.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            openInBrowser(instance);
            return true;
        }
    });

    Preference serverRemoveServerPreference = new Preference(context);
    serverRemoveServerPreference.setKey(Constants.PREFERENCES_KEY_SERVER_REMOVE + instance);
    serverRemoveServerPreference.setPersistent(false);
    serverRemoveServerPreference.setTitle(R.string.settings_servers_remove);

    serverRemoveServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.confirmDialog(context, R.string.common_delete, screen.getTitle().toString(),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Reset values to null so when we ask for them again they are new
                            serverNamePreference.setText(null);
                            serverUrlPreference.setText(null);
                            serverUsernamePreference.setText(null);
                            serverPasswordPreference.setText(null);

                            // Don't use Util.getActiveServer since it is 0 if offline
                            int activeServer = Util.getPreferences(context)
                                    .getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
                            for (int i = instance; i <= serverCount; i++) {
                                Util.removeInstanceName(context, i, activeServer);
                            }

                            serverCount--;
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                            editor.commit();

                            removeCurrent();

                            SubsonicFragment parentFragment = context.getCurrentFragment();
                            if (parentFragment instanceof SettingsFragment) {
                                SettingsFragment serverSelectionFragment = (SettingsFragment) parentFragment;
                                serverSelectionFragment.checkForRemoved();
                            }
                        }
                    });

            return true;
        }
    });

    Preference serverTestConnectionPreference = new Preference(context);
    serverTestConnectionPreference.setKey(Constants.PREFERENCES_KEY_TEST_CONNECTION + instance);
    serverTestConnectionPreference.setPersistent(false);
    serverTestConnectionPreference.setTitle(R.string.settings_test_connection_title);
    serverTestConnectionPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            testConnection(instance);
            return false;
        }
    });

    screen.addPreference(serverNamePreference);
    screen.addPreference(serverUrlPreference);
    screen.addPreference(serverInternalUrlPreference);
    screen.addPreference(serverLocalNetworkSSIDPreference);
    screen.addPreference(serverUsernamePreference);
    screen.addPreference(serverPasswordPreference);
    screen.addPreference(serverSyncPreference);
    screen.addPreference(serverTestConnectionPreference);
    screen.addPreference(serverOpenBrowser);
    screen.addPreference(serverRemoveServerPreference);

    return screen;
}

From source file:github.daneren2005.dsub.fragments.SettingsFragment.java

private PreferenceScreen expandServer(final int instance) {
    final PreferenceScreen screen = this.getPreferenceManager().createPreferenceScreen(context);
    screen.setTitle(R.string.settings_server_unused);
    screen.setKey(Constants.PREFERENCES_KEY_SERVER_KEY + instance);

    final EditTextPreference serverNamePreference = new EditTextPreference(context);
    serverNamePreference.setKey(Constants.PREFERENCES_KEY_SERVER_NAME + instance);
    serverNamePreference.setDefaultValue(getResources().getString(R.string.settings_server_unused));
    serverNamePreference.setTitle(R.string.settings_server_name);
    serverNamePreference.setDialogTitle(R.string.settings_server_name);

    if (serverNamePreference.getText() == null) {
        serverNamePreference.setText(getResources().getString(R.string.settings_server_unused));
    }//from   w w  w  . j a v  a2 s. co  m

    serverNamePreference.setSummary(serverNamePreference.getText());

    final EditTextPreference serverUrlPreference = new EditTextPreference(context);
    serverUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_URL + instance);
    serverUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverUrlPreference.setDefaultValue("http://yourhost");
    serverUrlPreference.setTitle(R.string.settings_server_address);
    serverUrlPreference.setDialogTitle(R.string.settings_server_address);

    if (serverUrlPreference.getText() == null) {
        serverUrlPreference.setText("http://yourhost");
    }

    serverUrlPreference.setSummary(serverUrlPreference.getText());
    screen.setSummary(serverUrlPreference.getText());

    final EditTextPreference serverLocalNetworkSSIDPreference = new EditTextPreference(context) {
        @Override
        protected void onAddEditTextToDialogView(View dialogView, final EditText editText) {
            super.onAddEditTextToDialogView(dialogView, editText);
            ViewGroup root = (ViewGroup) ((ViewGroup) dialogView).getChildAt(0);

            Button defaultButton = new Button(getContext());
            defaultButton.setText(internalSSIDDisplay);
            defaultButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editText.setText(internalSSID);
                }
            });
            root.addView(defaultButton);
        }
    };
    serverLocalNetworkSSIDPreference.setKey(Constants.PREFERENCES_KEY_SERVER_LOCAL_NETWORK_SSID + instance);
    serverLocalNetworkSSIDPreference.setTitle(R.string.settings_server_local_network_ssid);
    serverLocalNetworkSSIDPreference.setDialogTitle(R.string.settings_server_local_network_ssid);

    final EditTextPreference serverInternalUrlPreference = new EditTextPreference(context);
    serverInternalUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance);
    serverInternalUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverInternalUrlPreference.setDefaultValue("");
    serverInternalUrlPreference.setTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setDialogTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setSummary(serverInternalUrlPreference.getText());

    final EditTextPreference serverUsernamePreference = new EditTextPreference(context);
    serverUsernamePreference.setKey(Constants.PREFERENCES_KEY_USERNAME + instance);
    serverUsernamePreference.setTitle(R.string.settings_server_username);
    serverUsernamePreference.setDialogTitle(R.string.settings_server_username);

    final EditTextPreference serverPasswordPreference = new EditTextPreference(context);
    serverPasswordPreference.setKey(Constants.PREFERENCES_KEY_PASSWORD + instance);
    serverPasswordPreference.getEditText()
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    serverPasswordPreference.setSummary("***");
    serverPasswordPreference.setTitle(R.string.settings_server_password);

    final CheckBoxPreference serverTagPreference = new CheckBoxPreference(context);
    serverTagPreference.setKey(Constants.PREFERENCES_KEY_BROWSE_TAGS + instance);
    serverTagPreference.setChecked(Util.isTagBrowsing(context, instance));
    serverTagPreference.setSummary(R.string.settings_browse_by_tags_summary);
    serverTagPreference.setTitle(R.string.settings_browse_by_tags);
    serverPasswordPreference.setDialogTitle(R.string.settings_server_password);

    final CheckBoxPreference serverSyncPreference = new CheckBoxPreference(context);
    serverSyncPreference.setKey(Constants.PREFERENCES_KEY_SERVER_SYNC + instance);
    serverSyncPreference.setChecked(Util.isSyncEnabled(context, instance));
    serverSyncPreference.setSummary(R.string.settings_server_sync_summary);
    serverSyncPreference.setTitle(R.string.settings_server_sync);

    final Preference serverOpenBrowser = new Preference(context);
    serverOpenBrowser.setKey(Constants.PREFERENCES_KEY_OPEN_BROWSER);
    serverOpenBrowser.setPersistent(false);
    serverOpenBrowser.setTitle(R.string.settings_server_open_browser);
    serverOpenBrowser.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            openInBrowser(instance);
            return true;
        }
    });

    Preference serverRemoveServerPreference = new Preference(context);
    serverRemoveServerPreference.setKey(Constants.PREFERENCES_KEY_SERVER_REMOVE + instance);
    serverRemoveServerPreference.setPersistent(false);
    serverRemoveServerPreference.setTitle(R.string.settings_servers_remove);

    serverRemoveServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.confirmDialog(context, R.string.common_delete, screen.getTitle().toString(),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Reset values to null so when we ask for them again they are new
                            serverNamePreference.setText(null);
                            serverUrlPreference.setText(null);
                            serverUsernamePreference.setText(null);
                            serverPasswordPreference.setText(null);

                            // Don't use Util.getActiveServer since it is 0 if offline
                            int activeServer = Util.getPreferences(context)
                                    .getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
                            for (int i = instance; i <= serverCount; i++) {
                                Util.removeInstanceName(context, i, activeServer);
                            }

                            serverCount--;
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                            editor.commit();

                            removeCurrent();

                            SubsonicFragment parentFragment = context.getCurrentFragment();
                            if (parentFragment instanceof SettingsFragment) {
                                SettingsFragment serverSelectionFragment = (SettingsFragment) parentFragment;
                                serverSelectionFragment.checkForRemoved();
                            }
                        }
                    });

            return true;
        }
    });

    Preference serverTestConnectionPreference = new Preference(context);
    serverTestConnectionPreference.setKey(Constants.PREFERENCES_KEY_TEST_CONNECTION + instance);
    serverTestConnectionPreference.setPersistent(false);
    serverTestConnectionPreference.setTitle(R.string.settings_test_connection_title);
    serverTestConnectionPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            testConnection(instance);
            return false;
        }
    });

    screen.addPreference(serverNamePreference);
    screen.addPreference(serverUrlPreference);
    screen.addPreference(serverInternalUrlPreference);
    screen.addPreference(serverLocalNetworkSSIDPreference);
    screen.addPreference(serverUsernamePreference);
    screen.addPreference(serverPasswordPreference);
    screen.addPreference(serverTagPreference);
    screen.addPreference(serverSyncPreference);
    screen.addPreference(serverTestConnectionPreference);
    screen.addPreference(serverOpenBrowser);
    screen.addPreference(serverRemoveServerPreference);

    return screen;
}

From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java

private void addPasscodePreference(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context);
    passScreen.setTitle("4chan pass");
    EditTextPreference passTokenPreference = new EditTextPreference(context);
    EditTextPreference passPINPreference = new EditTextPreference(context);
    Preference passLoginPreference = new Preference(context);
    Preference passClearPreference = new Preference(context);
    passTokenPreference.setTitle("Token");
    passTokenPreference.setDialogTitle("Token");
    passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN));
    passTokenPreference.getEditText().setSingleLine();
    passTokenPreference.getEditText()//from   w ww. j a v  a  2s.com
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    passPINPreference.setTitle("PIN");
    passPINPreference.setDialogTitle("PIN");
    passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN));
    passPINPreference.getEditText().setSingleLine();
    passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    passLoginPreference.setTitle("Log In");
    passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!useHttps())
                Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show();
            final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), "");
            final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), "");
            final String authUrl = "https://sys.4chan.org/auth"; //only https
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        setPasscodeCookie(null, true);
                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                        pairs.add(new BasicNameValuePair("act", "do_login"));
                        pairs.add(new BasicNameValuePair("id", token));
                        pairs.add(new BasicNameValuePair("pin", pin));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request,
                                httpClient, null, passAuthTask, false);
                        if (passAuthTask.isCancelled())
                            return;
                        if (response.contains("Your device is now authorized")) {
                            String passId = null;
                            for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
                                if (cookie.getName().equals("pass_id")) {
                                    String value = cookie.getValue();
                                    if (!value.equals("0")) {
                                        passId = value;
                                        break;
                                    }
                                }
                            }
                            if (passId == null) {
                                showToast("Could not get pass id");
                            } else {
                                setPasscodeCookie(passId, true);
                                showToast("Success! Your device is now authorized.");
                            }
                        } else if (response.contains("Your Token must be exactly 10 characters")) {
                            showToast("Incorrect token");
                        } else if (response.contains("You have left one or more fields blank")) {
                            showToast("You have left one or more fields blank");
                        } else if (response.contains("Incorrect Token or PIN")) {
                            showToast("Incorrect Token or PIN");
                        } else {
                            Matcher m = Pattern
                                    .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>")
                                    .matcher(response);
                            if (m.find()) {
                                showToast(m.group(1));
                            } else {
                                showWebView(response);
                            }
                        }
                    } catch (Exception e) {
                        showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown)
                                : e.getMessage());
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }

                private void showToast(final String message) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                private void showWebView(final String html) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                WebView webView = new WebView(context);
                                webView.getSettings().setSupportZoom(true);
                                webView.loadData(html, "text/html", null);
                                new AlertDialog.Builder(context).setView(webView)
                                        .setNeutralButton(android.R.string.ok, null).show();
                            }
                        });
                    }
                }
            });
            return true;
        }
    });
    passClearPreference.setTitle("Reset pass cookie");
    passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            setPasscodeCookie(null, true);
            Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show();
            return true;
        }
    });
    passScreen.addPreference(passTokenPreference);
    passScreen.addPreference(passPINPreference);
    passScreen.addPreference(passLoginPreference);
    passScreen.addPreference(passClearPreference);
    preferenceGroup.addPreference(passScreen);
}

From source file:com.master.metehan.filtereagle.ActivitySettings.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceCategory cat_options = (PreferenceCategory) screen.findPreference("category_options");
    PreferenceCategory cat_advanced = (PreferenceCategory) screen.findPreference("category_advanced_options");
    PreferenceCategory cat_backup = (PreferenceCategory) screen.findPreference("category_backup");
    PreferenceCategory cat_development = (PreferenceCategory) screen.findPreference("category_development");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }/*from ww w. j  av a  2 s. c o  m*/

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssid = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssid.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssid)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    // Filtering always enabled
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        cat_advanced.removePreference(screen.findPreference("filter"));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.execute();
                }
            });
            return false;
        }
    });

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns = (EditTextPreference) screen.findPreference("dns");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns.getEditText().setHint(def_dns.get(0));
    pref_dns.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Handle stats
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    if (Util.isPlayStoreInstall(this)) {
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        pref_block_domains.setEnabled(new File(getFilesDir(), "hosts.txt").exists());

        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        getPreferenceScreen().findPreference("use_hosts").setEnabled(true);
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
                                }

                                @Override
                                public void onCancelled() {
                                    if (tmp.exists())
                                        tmp.delete();
                                }

                                @Override
                                public void onException(Throwable ex) {
                                    if (tmp.exists())
                                        tmp.delete();

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).execute();
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (!(Util.isDebuggable(this) || Util.getSelfVersionName(this).contains("beta"))) {
        screen.removePreference(cat_development);
        prefs.edit().remove("loglevel").apply();
    } else if (!Util.isDebuggable(this))
        cat_development.removePreference(pref_show_resolved);

    // Show resolved
    pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
            return true;
        }
    });

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    Preference pref_technical_subscription = screen.findPreference("technical_subscription");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    pref_technical_subscription.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();
}