Example usage for android.preference ListPreference findIndexOfValue

List of usage examples for android.preference ListPreference findIndexOfValue

Introduction

In this page you can find the example usage for android.preference ListPreference findIndexOfValue.

Prototype

public int findIndexOfValue(String value) 

Source Link

Document

Returns the index of the given value (in the entry values array).

Usage

From source file:com.vonglasow.michael.satstat.SettingsActivity.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(SettingsActivity.KEY_PREF_NOTIFY_FIX)
            || key.equals(SettingsActivity.KEY_PREF_NOTIFY_SEARCH)) {
        boolean notifyFix = sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_NOTIFY_FIX, false);
        boolean notifySearch = sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_NOTIFY_SEARCH, false);
        if (!(notifyFix || notifySearch)) {
            Intent stopServiceIntent = new Intent(this, PasvLocListenerService.class);
            this.stopService(stopServiceIntent);
        }/*w w w. ja va2  s .  co m*/
    } else if (key.equals(SettingsActivity.KEY_PREF_UPDATE_FREQ)) {
        // this piece of code is necessary because Android has no way
        // of updating the preference summary automatically. I am
        // told the absence of such functionality is a feature...
        SettingsFragment sf = (SettingsFragment) getFragmentManager().findFragmentById(android.R.id.content);
        ListPreference prefUpdateFreq = (ListPreference) sf.findPreference(KEY_PREF_UPDATE_FREQ);
        final String value = sharedPreferences.getString(key, key);
        final int index = prefUpdateFreq.findIndexOfValue(value);
        if (index >= 0) {
            final String summary = (String) prefUpdateFreq.getEntries()[index];
            prefUpdateFreq.setSummary(summary);
        }
    }
}

From source file:com.jmstudios.redmoon.fragment.ShadesFragment.java

private boolean onAutomaticFilterPreferenceChange(Preference preference, Object newValue) {
    if (newValue.toString().equals("sun") && ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(),
                new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, 0);
        return false;
    }/*from   w  w w.  j ava2s. c  o m*/

    boolean custom = newValue.toString().equals("custom");
    automaticTurnOnPref.setEnabled(custom);
    automaticTurnOffPref.setEnabled(custom);

    boolean sun = newValue.toString().equals("sun");
    locationPref.setEnabled(sun);

    // From something to sun
    if (newValue.toString().equals("sun")) {
        // Update the FilterTimePreferences
        updateFilterTimesFromSun();

        // Attempt to get a new location
        locationPref.searchLocation(false);
    }

    // From sun to something
    String oldValue = preference.getSharedPreferences().getString(preference.getKey(), "never");
    if (oldValue.equals("sun") && !newValue.equals("sun")) {
        automaticTurnOnPref.setToCustomTime();
        automaticTurnOffPref.setToCustomTime();
    }

    ListPreference lp = (ListPreference) preference;
    String entry = lp.getEntries()[lp.findIndexOfValue(newValue.toString())].toString();
    lp.setSummary(entry);

    return true;
}

From source file:com.example.weather.SettingsActivity.java

private void setPreferenceSummary(Preference preference, Object value) {
    String stringValue = value.toString();
    String key = preference.getKey();

    if (preference instanceof ListPreference) {
        // For list preferences, look up the correct display value in
        // the preference's 'entries' list (since they have separate labels/values).
        ListPreference listPreference = (ListPreference) preference;
        int prefIndex = listPreference.findIndexOfValue(stringValue);
        if (prefIndex >= 0) {
            preference.setSummary(listPreference.getEntries()[prefIndex]);
        }//from   w ww.j a  va 2 s.c  o m
    } else if (key.equals(getString(R.string.pref_location_key))) {
        @WeatherSyncAdapter.LocationStatus
        int status = Utility.getLocationStatus(this);
        switch (status) {
        case WeatherSyncAdapter.LOCATION_STATUS_OK:
            preference.setSummary(stringValue);
            break;
        case WeatherSyncAdapter.LOCATION_STATUS_UNKNOWN:
            preference.setSummary(getString(R.string.pref_location_unknown_description, value.toString()));
            break;
        case WeatherSyncAdapter.LOCATION_STATUS_INVALID:
            preference.setSummary(getString(R.string.pref_location_error_description, value.toString()));
            break;
        default:
            // Note --- if the server is down we still assume the value
            // is valid
            preference.setSummary(stringValue);

        case WeatherSyncAdapter.LOCATION_STATUS_SERVER_DOWN:
            break;
        case WeatherSyncAdapter.LOCATION_STATUS_SERVER_INVALID:
            break;
        }
    } else {
        // For other preferences, set the summary to the value's simple string representation.
        preference.setSummary(stringValue);
    }

}

From source file:com.schoentoon.connectbot.HostEditorActivity.java

private void updateSummaries() {
    // for all text preferences, set hint as current database value
    for (String key : this.pref.values.keySet()) {
        if (key.equals(HostDatabase.FIELD_HOST_POSTLOGIN))
            continue;
        Preference pref = this.findPreference(key);
        if (pref == null)
            continue;
        if (pref instanceof CheckBoxPreference)
            continue;
        CharSequence value = this.pref.getString(key, "");

        if (key.equals(HostDatabase.FIELD_HOST_PUBKEYID)) {
            try {
                int pubkeyId = Integer.parseInt((String) value);
                if (pubkeyId >= 0)
                    pref.setSummary(pubkeydb.getNickname(pubkeyId));
                else if (pubkeyId == HostDatabase.PUBKEYID_ANY)
                    pref.setSummary(R.string.list_pubkeyids_any);
                else if (pubkeyId == HostDatabase.PUBKEYID_NEVER)
                    pref.setSummary(R.string.list_pubkeyids_none);
                continue;
            } catch (NumberFormatException nfe) {
                // Fall through.
            }//from   ww  w  .  j  a  v  a2 s  . co  m
        } else if (pref instanceof ListPreference) {
            ListPreference listPref = (ListPreference) pref;
            int entryIndex = listPref.findIndexOfValue((String) value);
            if (entryIndex >= 0)
                value = listPref.getEntries()[entryIndex];
        }

        pref.setSummary(value);
    }

}

From source file:org.dmfs.webcal.fragments.PreferencesFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.webcal_preference);
    ListPreference locales = (ListPreference) findPreference("content_location");

    locales.setOnPreferenceChangeListener(PrefUpdater);

    try {//from w ww  .  ja  v a 2 s  .  c  om
        getCountries();

        locales.setEntries(mCountryNames);
        locales.setEntryValues(mCountryCodes);
    } catch (Exception e) {
        Log.e(TAG, "could not load country list", e);
    }

    int index = locales.findIndexOfValue(locales.getValue());
    if (index >= 0) {
        locales.setSummary(locales.getEntries()[index]);
    } else {
        locales.setSummary(locales.getEntries()[0]);
        locales.setValueIndex(0);
    }
}

From source file:com.vonglasow.michael.satstat.ui.SettingsActivity.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    boolean needsLocationPerm = false;
    if (key.equals(Const.KEY_PREF_NOTIFY_FIX) || key.equals(Const.KEY_PREF_NOTIFY_SEARCH)) {
        boolean notifyFix = sharedPreferences.getBoolean(Const.KEY_PREF_NOTIFY_FIX, false);
        boolean notifySearch = sharedPreferences.getBoolean(Const.KEY_PREF_NOTIFY_SEARCH, false);
        if (!(notifyFix || notifySearch)) {
            Intent stopServiceIntent = new Intent(this, PasvLocListenerService.class);
            this.stopService(stopServiceIntent);
        } else if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            needsLocationPerm = true;//from  w  w w  .jav a  2 s.  c  om
        }
    } else if (key.equals(Const.KEY_PREF_UPDATE_FREQ)) {
        // this piece of code is necessary because Android has no way
        // of updating the preference summary automatically. I am
        // told the absence of such functionality is a feature...
        SettingsFragment sf = (SettingsFragment) getFragmentManager().findFragmentById(android.R.id.content);
        ListPreference prefUpdateFreq = (ListPreference) sf.findPreference(Const.KEY_PREF_UPDATE_FREQ);
        final String value = sharedPreferences.getString(key, key);
        final int index = prefUpdateFreq.findIndexOfValue(value);
        if (index >= 0) {
            final String summary = (String) prefUpdateFreq.getEntries()[index];
            prefUpdateFreq.setSummary(summary);
        }
    } else if (key.equals(Const.KEY_PREF_MAP_PATH)) {
        SettingsFragment sf = (SettingsFragment) getFragmentManager().findFragmentById(android.R.id.content);
        Preference prefMapPath = sf.findPreference(Const.KEY_PREF_MAP_PATH);
        prefMapPathValue = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPathValue);
        prefMapPath.setSummary(prefMapPathValue);
    } else if (key.equals(Const.KEY_PREF_UPDATE_NETWORKS)) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Set<String> updateNetworks = sharedPreferences.getStringSet(Const.KEY_PREF_UPDATE_NETWORKS,
                    new HashSet<String>());
            if (!updateNetworks.isEmpty())
                needsLocationPerm = true;
        }
    }
    if (needsLocationPerm)
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                Const.PERM_REQUEST_LOCATION_PREF);
}

From source file:de.k3b.android.toGoZip.SettingsActivity.java

private void setPref(String key, ListPreference listPreference, int arrayResourceId) {
    int index = listPreference.findIndexOfValue(key);
    String summary = "";

    if (index >= 0) {
        String[] names = this.getResources().getStringArray(arrayResourceId);
        if (index < names.length) {
            summary = names[index];/* w  w  w.j a  v a2  s  .co m*/
        }
    }
    listPreference.setSummary(summary);

}

From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (preference.getKey().equals(KEY_PREF_PROXY_SERVER)) {
        preference.setSummary((String) newValue);
    } else if (preference.getKey().equals(KEY_PREF_VIEW_DIRECTION)) {
        ListPreference directionPreference = (ListPreference) preference;
        CharSequence[] entries = directionPreference.getEntries();
        int i = directionPreference.findIndexOfValue((String) newValue);
        i = (i <= 0) ? 0 : i;/*  w ww  .  j av a  2  s . c o m*/
        directionPreference.setSummary(entries[i]);
    } else if (preference.getKey().equals(KEY_PREF_VIEW_VIDEO_PLAYER)) {
        ListPreference videoPlayerPreference = (ListPreference) preference;
        CharSequence[] entries = videoPlayerPreference.getEntries();
        int i = videoPlayerPreference.findIndexOfValue((String) newValue);
        i = (i <= 0) ? 0 : i;
        videoPlayerPreference.setSummary(entries[i]);
        if (VIDEO_IJKPLAYER.equals(newValue) && !DynamicIjkLibLoader.isLibrariesDownloaded()) {
            // ?so
            new DynamicLibDownloader(activity).checkDownloadLib();
        }
    }
    return true;
}

From source file:be.deadba.ampd.SettingsActivity.java

/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.//w  w w. j a  va 2 s  .c  om
 */
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
    String stringValue = value.toString();
    String key = preference.getKey();
    Log.d(TAG, "onPreferenceChange: key: " + key + " / value: " + stringValue);

    if (preference.isPersistent()) {
        Editor editor = MPDConf.getSharedPreferences(this).edit();
        if (value instanceof Boolean)
            editor.putBoolean(key, (Boolean) value);
        else
            editor.putString(key, (String) value);
        editor.commit();
    }
    if (key.equals("run")) {
        mRunPreference = (TwoStatePreference) preference;
        mRun = stringValue.equals("true");
        onMPDStatePreferenceChange(false);
        return true;
    }
    if (key.equals("run_on_boot")) {
        mRunOnBootPreference = (TwoStatePreference) preference;
        mRunOnBoot = stringValue.equals("true");
        if (mRunOnBoot)
            mRun = true;
        onMPDStatePreferenceChange(false);
        return true;
    } else if (key.equals("wakelock")) {
        onMPDStatePreferenceChange(true);
        return true;
    } else if (key.equals("mpd_music_directory")) {
        File file = new File(stringValue);
        mDirValid = file.exists() && file.isDirectory() && file.canRead() && file.canExecute();
        onMPDStatePreferenceChange(true);
    } else if (key.equals("mpd_port")) {
        int port = 0;
        try {
            port = Integer.parseInt(stringValue);
        } catch (NumberFormatException e) {
        }
        mPortValid = port >= 1024 && port <= 65535;
        if (mPortValid)
            mPort = String.valueOf(port);
        onMPDStatePreferenceChange(true);
    } else if (key.equals("mpd_mixer")) {
        onMPDStatePreferenceChange(true);
        return true;
    } else if (key.equals("mpd_output")) {
        onMPDStatePreferenceChange(true);
    }
    if (preference instanceof ListPreference) {
        // For list preferences, look up the correct display value in
        // the preference's 'entries' list.
        ListPreference listPreference = (ListPreference) preference;
        int index = listPreference.findIndexOfValue(stringValue);

        // Set the summary to reflect the new value.
        preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
    } else {
        // For all other preferences, set the summary to the value's
        // simple string representation.
        preference.setSummary(stringValue);
    }

    return true;
}

From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPreferenceManager().setSharedPreferencesName(SharedPreferencesUtil.FILE_NAME);
    addPreferencesFromResource(R.xml.preferences);

    String downloadPath = DownloadManager.getDownloadPath();
    if (downloadPath != null) {
        String displayPath = Uri.decode(downloadPath);
        getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath);
    }/*from w ww . ja v a2s. c o  m*/
    ListPreference listPreference = (ListPreference) getPreferenceManager()
            .findPreference(KEY_PREF_VIEW_DIRECTION);
    CharSequence[] entries = listPreference.getEntries();
    int i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);
    listPreference = (ListPreference) getPreferenceManager().findPreference(KEY_PREF_VIEW_VIDEO_PLAYER);
    entries = listPreference.getEntries();
    i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);

    getPreferenceScreen().setOnPreferenceChangeListener(this);
    final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
            .initialDirectory((downloadPath.startsWith("/")) ? downloadPath : DownloadManager.DEFAULT_PATH)
            .newDirectoryName("download").allowNewDirectoryNameModification(true).build();
    mDialog = DirectoryChooserFragment.newInstance(config);
    mDialog.setTargetFragment(this, 0);

    float size = (float) Fresco.getImagePipelineFactory().getMainFileCache().getSize() / ByteConstants.MB;
    Preference cacheCleanPreference = getPreferenceManager().findPreference(KEY_PREF_CACHE_CLEAN);
    cacheCleanPreference.setSummary(String.format(" %.2f MB", size));

    LongClickPreference prefDownloadPath = (LongClickPreference) getPreferenceManager()
            .findPreference(KEY_PREF_DOWNLOAD_PATH);
    prefDownloadPath.setOnLongClickListener(v -> {
        new AlertDialog.Builder(activity).setTitle("?")
                .setItems(new String[] { "", "" },
                        (dialogInterface, pos) -> {
                            if (pos == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                                try {
                                    startActivityForResult(intent, RESULT_CHOOSE_DIRECTORY);
                                } catch (ActivityNotFoundException e) {
                                    e.printStackTrace();
                                    mDialog.show(getFragmentManager(), null);
                                }
                                new Handler().postDelayed(() -> {
                                    if (!opened)
                                        activity.showSnackBar(
                                                "?");
                                }, 1000);
                            } else if (pos == 1) {
                                mDialog.show(getFragmentManager(), null);
                            } else
                                activity.showSnackBar("???");
                        })
                .setNegativeButton(getString(R.string.cancel), null).show();
        return true;
    });
}