Example usage for android.preference EditTextPreference getText

List of usage examples for android.preference EditTextPreference getText

Introduction

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

Prototype

public String getText() 

Source Link

Document

Gets the text from the SharedPreferences .

Usage

From source file:org.linphone.AccountPreferencesFragment.java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.almalence.opencam.Fragment.java

private void initExportName(Preference preference, Object newValue) {
    EditTextPreference prefix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPrefixValue));
    String prefixValue = "";
    if (prefix != null) {
        if (preference != null && prefix.getKey().equals(preference.getKey())) {
            prefixValue = newValue.toString();
        } else {//from   w  w  w . j a  v a 2 s  .  c o  m
            prefixValue = prefix.getText();
        }

        if (!prefixValue.equals("")) {
            prefixValue = prefixValue + "_";
        }
    }

    EditTextPreference postfix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPostfixValue));
    String postfixValue = "";
    if (postfix != null) {
        if (preference != null && postfix.getKey().equals(preference.getKey())) {
            postfixValue = newValue.toString();
        } else {
            postfixValue = postfix.getText();
        }

        if (!postfixValue.equals("")) {
            postfixValue = "_" + postfixValue;
        }
    }

    ListPreference exportNameList = (ListPreference) this
            .findPreference(getResources().getString(R.string.Preference_ExportNameValue));
    if (exportNameList != null) {
        String[] names = MainScreen.getAppResources().getStringArray(R.array.exportNameArray);
        CharSequence[] newNames = new CharSequence[names.length];
        int i = 0;
        for (String name : names) {
            newNames[i] = prefixValue + name + postfixValue;
            i++;
        }
        exportNameList.setEntries(newNames);
        exportNameList.setSummary(exportNameList.getEntries()[Integer.parseInt(exportNameList.getValue()) - 1]);
    }
}

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));
    }//from   ww  w.  j  ava 2s .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));
    }/*ww  w  . j ava2s .  c  o 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.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  w  w w .j  a  v a  2  s  .  c  om*/

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

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;
        }//from ww  w .  j a  v a2  s  . c om

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

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;
        }/*from  www.ja v a  2s  .com*/

    // 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.adblocker.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   w w  w .  j  a  va 2s .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 {
        try {

            AssetManager am = getAssets();

            InputStream inputStream = getResources().openRawResource(R.raw.hosts);
            File hfile = createFileFromInputStream(inputStream);

            pref_block_domains.setEnabled(hfile.exists());
        } catch (Exception e) {
            e.printStackTrace();
        }

        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(), "host/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();
}