Example usage for android.preference PreferenceGroup removePreference

List of usage examples for android.preference PreferenceGroup removePreference

Introduction

In this page you can find the example usage for android.preference PreferenceGroup removePreference.

Prototype

public boolean removePreference(Preference preference) 

Source Link

Document

Removes a Preference from this group.

Usage

From source file:Main.java

/**
 * Removes a {@link Preference} from the {@link PreferenceCategory} with the given key.
 *///from www. j  a v a  2 s . c om
public static void removePreference(PreferenceFragment prefFrag, int parentKey, int prefKey) {
    String parentName = prefFrag.getString(parentKey);
    String prefName = prefFrag.getString(prefKey);
    PreferenceGroup parent = (PreferenceGroup) prefFrag.findPreference(parentName);
    Preference child = prefFrag.findPreference(prefName);

    if (parent != null && child != null) {
        parent.removePreference(child);
    }
}

From source file:com.android.inputmethod.latin.settings.CustomInputStyleSettingsFragment.java

@Override
public void onRemoveCustomInputStyle(final CustomInputStylePreference stylePref) {
    mIsAddingNewSubtype = false;//www  .  j  a  v  a  2  s . com
    final PreferenceGroup group = getPreferenceScreen();
    group.removePreference(stylePref);
    mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
}

From source file:com.android.inputmethod.latin.settings.CustomInputStyleSettingsFragment.java

@Override
public void onAddCustomInputStyle(final CustomInputStylePreference stylePref) {
    mIsAddingNewSubtype = false;/*from   w  ww  .  j a va  2  s. c  o  m*/
    final InputMethodSubtype subtype = stylePref.getSubtype();
    if (findDuplicatedSubtype(subtype) == null) {
        mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
        mSubtypePreferenceKeyForSubtypeEnabler = stylePref.getKey();
        mSubtypeEnablerNotificationDialog = createDialog();
        mSubtypeEnablerNotificationDialog.show();
        return;
    }

    // Newly added subtype is duplicated.
    final PreferenceGroup group = getPreferenceScreen();
    group.removePreference(stylePref);
    showSubtypeAlreadyExistsToast(subtype);
}

From source file:com.android.inputmethod.latin.settings.CustomInputStyleSettingsFragment.java

@Override
public void onSaveCustomInputStyle(final CustomInputStylePreference stylePref) {
    final InputMethodSubtype subtype = stylePref.getSubtype();
    if (!stylePref.hasBeenModified()) {
        return;/*from   ww  w . j av a  2s. co  m*/
    }
    if (findDuplicatedSubtype(subtype) == null) {
        mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
        return;
    }

    // Saved subtype is duplicated.
    final PreferenceGroup group = getPreferenceScreen();
    group.removePreference(stylePref);
    stylePref.revert();
    group.addPreference(stylePref);
    showSubtypeAlreadyExistsToast(subtype);
}

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

private void updateView() {

    // user id/*  w  ww .j a  v  a  2  s  . c  o 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:de.mrapp.android.preference.activity.PreferenceFragment.java

/**
 * Restores the default preferences, which are contained by a specific preference group.
 *
 * @param preferenceGroup//from  www.ja  v  a  2 s .c  o  m
 *         The preference group, whose preferences should be restored, as an instance of the
 *         class {@link PreferenceGroup}. The preference group may not be null
 * @param sharedPreferences
 *         The shared preferences, which should be used to restore the preferences, as an
 *         instance of the type {@link SharedPreferences}. The shared preferences may not be
 *         null
 */
private void restoreDefaults(@NonNull final PreferenceGroup preferenceGroup,
        @NonNull final SharedPreferences sharedPreferences) {
    for (int i = 0; i < preferenceGroup.getPreferenceCount(); i++) {
        Preference preference = preferenceGroup.getPreference(i);

        if (preference instanceof PreferenceGroup) {
            restoreDefaults((PreferenceGroup) preference, sharedPreferences);
        } else if (preference.getKey() != null && !preference.getKey().isEmpty()) {
            Object oldValue = sharedPreferences.getAll().get(preference.getKey());

            if (notifyOnRestoreDefaultValueRequested(preference, oldValue)) {
                sharedPreferences.edit().remove(preference.getKey()).apply();
                preferenceGroup.removePreference(preference);
                preferenceGroup.addPreference(preference);
                Object newValue = sharedPreferences.getAll().get(preference.getKey());
                notifyOnRestoredDefaultValue(preference, oldValue, newValue);
            } else {
                preferenceGroup.removePreference(preference);
                preferenceGroup.addPreference(preference);
            }

        }
    }
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

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

    PreferenceGroup cat_options = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_options"))
            .findPreference("category_options");
    PreferenceGroup cat_advanced = (PreferenceGroup) ((PreferenceGroup) screen
            .findPreference("screen_advanced_options")).findPreference("category_advanced_options");
    PreferenceGroup cat_stats = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_stats"))
            .findPreference("category_stats");
    PreferenceGroup cat_backup = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_backup"))
            .findPreference("category_backup");

    // 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;
        }// w w w  .  ja va 2  s .  c  o  m

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

    WifiManager wm = (WifiManager) getApplicationContext().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);
    for (String ssid : ssids)
        if (!listSSID.contains(ssid))
            listSSID.add(ssid);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    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_dns1 = (EditTextPreference) screen.findPreference("dns");
    EditTextPreference pref_dns2 = (EditTextPreference) screen.findPreference("dns2");
    EditTextPreference pref_ttl = (EditTextPreference) screen.findPreference("ttl");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns1.getEditText().setHint(def_dns.get(0));
    pref_dns2.getEditText().setHint(def_dns.get(1));
    pref_dns1.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));
    pref_dns2.setTitle(getString(R.string.setting_dns, prefs.getString("dns2", def_dns.get(1))));
    pref_ttl.setTitle(getString(R.string.setting_ttl, prefs.getString("ttl", "259200")));

    // SOCKS5 parameters
    screen.findPreference("socks5_addr")
            .setTitle(getString(R.string.setting_socks5_addr, prefs.getString("socks5_addr", "-")));
    screen.findPreference("socks5_port")
            .setTitle(getString(R.string.setting_socks5_port, prefs.getString("socks5_port", "-")));
    screen.findPreference("socks5_username")
            .setTitle(getString(R.string.setting_socks5_username, prefs.getString("socks5_username", "-")));
    screen.findPreference("socks5_password").setTitle(getString(R.string.setting_socks5_password,
            TextUtils.isEmpty(prefs.getString("socks5_username", "")) ? "-" : "*****"));

    // 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")));

    // Watchdog
    screen.findPreference("watchdog")
            .setTitle(getString(R.string.setting_watchdog, prefs.getString("watchdog", "0")));

    // Show resolved
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (Util.isPlayStoreInstall(this))
        cat_advanced.removePreference(pref_show_resolved);
    else
        pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
                return true;
            }
        });

    // Handle stats
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        cat_stats.removePreference(screen.findPreference("show_top"));
    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");
    EditTextPreference pref_rcode = (EditTextPreference) screen.findPreference("rcode");
    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");

    pref_rcode.setTitle(getString(R.string.setting_rcode, prefs.getString("rcode", "3")));

    if (Util.isPlayStoreInstall(this)) {
        Log.i(TAG, "Play store install");
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_rcode);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        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) {
                                        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
    if (!Util.isDebuggable(this))
        screen.removePreference(screen.findPreference("screen_development"));

    // 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();

    //        markPro(screen.findPreference("theme"), ActivityPro.SKU_THEME);
    //        markPro(screen.findPreference("install"), ActivityPro.SKU_NOTIFY);
    //        markPro(screen.findPreference("show_stats"), ActivityPro.SKU_SPEED);
}

From source file:eu.faircode.netguard.ActivitySettings.java

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

    PreferenceGroup cat_options = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_options"))
            .findPreference("category_options");
    PreferenceGroup cat_advanced = (PreferenceGroup) ((PreferenceGroup) screen
            .findPreference("screen_advanced_options")).findPreference("category_advanced_options");
    PreferenceGroup cat_stats = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_stats"))
            .findPreference("category_stats");
    PreferenceGroup cat_backup = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_backup"))
            .findPreference("category_backup");

    // 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;
        }/*  ww w . j  a  v  a 2  s .  co  m*/

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

    WifiManager wm = (WifiManager) getApplicationContext().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);
    for (String ssid : ssids)
        if (!listSSID.contains(ssid))
            listSSID.add(ssid);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    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();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
            return false;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        TwoStatePreference pref_reload_onconnectivity = (TwoStatePreference) screen
                .findPreference("reload_onconnectivity");
        pref_reload_onconnectivity.setChecked(true);
        pref_reload_onconnectivity.setEnabled(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;
        }
    });

    boolean can = Util.canFilter(this);
    TwoStatePreference pref_log_app = (TwoStatePreference) screen.findPreference("log_app");
    TwoStatePreference pref_filter = (TwoStatePreference) screen.findPreference("filter");
    pref_log_app.setEnabled(can);
    pref_filter.setEnabled(can);
    if (!can) {
        pref_log_app.setSummary(R.string.msg_unavailable);
        pref_filter.setSummary(R.string.msg_unavailable);
    }

    // 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_dns1 = (EditTextPreference) screen.findPreference("dns");
    EditTextPreference pref_dns2 = (EditTextPreference) screen.findPreference("dns2");
    EditTextPreference pref_ttl = (EditTextPreference) screen.findPreference("ttl");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns1.getEditText().setHint(def_dns.get(0));
    pref_dns2.getEditText().setHint(def_dns.get(1));
    pref_dns1.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));
    pref_dns2.setTitle(getString(R.string.setting_dns, prefs.getString("dns2", def_dns.get(1))));
    pref_ttl.setTitle(getString(R.string.setting_ttl, prefs.getString("ttl", "259200")));

    // SOCKS5 parameters
    screen.findPreference("socks5_addr")
            .setTitle(getString(R.string.setting_socks5_addr, prefs.getString("socks5_addr", "-")));
    screen.findPreference("socks5_port")
            .setTitle(getString(R.string.setting_socks5_port, prefs.getString("socks5_port", "-")));
    screen.findPreference("socks5_username")
            .setTitle(getString(R.string.setting_socks5_username, prefs.getString("socks5_username", "-")));
    screen.findPreference("socks5_password").setTitle(getString(R.string.setting_socks5_password,
            TextUtils.isEmpty(prefs.getString("socks5_username", "")) ? "-" : "*****"));

    // 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")));

    // Watchdog
    screen.findPreference("watchdog")
            .setTitle(getString(R.string.setting_watchdog, prefs.getString("watchdog", "0")));

    // Show resolved
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (Util.isPlayStoreInstall(this))
        cat_advanced.removePreference(pref_show_resolved);
    else
        pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
                return true;
            }
        });

    // Handle stats
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        cat_stats.removePreference(screen.findPreference("show_top"));
    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");
    EditTextPreference pref_rcode = (EditTextPreference) screen.findPreference("rcode");
    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");

    pref_rcode.setTitle(getString(R.string.setting_rcode, prefs.getString("rcode", "3")));

    if (Util.isPlayStoreInstall(this)) {
        Log.i(TAG, "Play store install");
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_rcode);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        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) {
                                        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, false);
                                }

                                @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();
                                }
                            }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    if (!Util.isDebuggable(this))
        screen.removePreference(screen.findPreference("screen_development"));

    // 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");
    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);
    updateTechnicalInfo();

    markPro(screen.findPreference("theme"), ActivityPro.SKU_THEME);
    markPro(screen.findPreference("install"), ActivityPro.SKU_NOTIFY);
    markPro(screen.findPreference("show_stats"), ActivityPro.SKU_SPEED);
}