java - Android ListPreference不保存选择

标签 java android sharedpreferences preferences listpreference

我显示了一个可选列表,其中包含所有可启动的已安装应用程序。我不想保存选择,但 ListPreference 保存了所有列出的条目。

我的错误在哪里?

这是我的列表首选项:

公共(public)类SettingsSelectsApps扩展ListPreference{

private String separator;
private static final String DEFAULT_SEPARATOR = "\u0001\u0007\u001D\u0007\u0001";
private boolean[] entryChecked;

public SettingsSelectsApps(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    loadEntries();
    entryChecked = new boolean[getEntries().length];
    separator = DEFAULT_SEPARATOR;
}

public SettingsSelectsApps(Context context) {
    this(context, null);
}

private void loadEntries() {

    final Context context = getContext();

    final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

    CharSequence[] entries = new CharSequence[pkgAppsList.size()];
    CharSequence[] entryValues = new CharSequence[pkgAppsList.size()]; 

    int j = 0;

    for ( ResolveInfo P : pkgAppsList ) {
        entryValues[j] = (CharSequence) P.getClass().getName();
        entries[j] = P.loadLabel(context.getPackageManager());
        ++j;
    };

    setEntries(entries);
    setEntryValues(entryValues);
}

@Override
protected void onPrepareDialogBuilder(Builder builder) {
    CharSequence[] entries = getEntries();
    CharSequence[] entryValues = getEntryValues();       

    if (entries == null || entryValues == null || entries.length != entryValues.length) {
        throw new IllegalStateException(
                "MultiSelectListPreference requires an entries array and an entryValues "
                        + "array which are both the same length");
    }

    restoreCheckedEntries();
    OnMultiChoiceClickListener listener = new DialogInterface.OnMultiChoiceClickListener() {
        public void onClick(DialogInterface dialog, int which, boolean val) {
            entryChecked[which] = val;
        }
    };
    builder.setMultiChoiceItems(entries, entryChecked, listener);
}

private CharSequence[] unpack(CharSequence val) {
    if (val == null || "".equals(val)) {
        return new CharSequence[0];
    } else {
        return ((String) val).split(separator);
    }
}

public CharSequence[] getCheckedValues() {
    return unpack(getValue());
}

private void restoreCheckedEntries() {
    CharSequence[] entryValues = getEntryValues();
    CharSequence[] vals = unpack(getValue());

    if (vals != null) {
        List<CharSequence> valuesList = Arrays.asList(vals);
        for (int i = 0; i < entryValues.length; i++) {
            CharSequence entry = entryValues[i];
            entryChecked[i] = valuesList.contains(entry);
        }
    }

    SharedPreferences prefs = getSharedPreferences();
    try{
      Map<String,?> keys = prefs.getAll();

        for(Map.Entry<String,?> entry : keys.entrySet()){          
         }
    } catch(NullPointerException e) {
        Log.d("map values","Error: "+e);
    }
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    List<CharSequence> values = new ArrayList<CharSequence>();

    CharSequence[] entryValues = getEntryValues();
    if (positiveResult && entryValues != null) {
        for (int i = 0; i < entryValues.length; i++) {
            if (entryChecked[i] == true) {
                String val = (String) entryValues[i];
                values.add(val);
            }
        }

        String value = join(values, separator);
        setSummary(prepareSummary(values));
        setValueAndEvent(value);
    }
}

private void setValueAndEvent(String value) {
    if (callChangeListener(unpack(value))) {
        setValue(value);
    }
}

private CharSequence prepareSummary(List<CharSequence> joined) {
    List<String> titles = new ArrayList<String>();
    CharSequence[] entryTitle = getEntries();
    CharSequence[] entryValues = getEntryValues();
    int ix = 0;
    for (CharSequence value : entryValues) {
        if (joined.contains(value)) {
            titles.add((String) entryTitle[ix]);
        }
        ix += 1;
    }
    return join(titles, ", ");
}

@Override
protected Object onGetDefaultValue(TypedArray typedArray, int index) {
    return typedArray.getTextArray(index);
}

@Override
protected void onSetInitialValue(boolean restoreValue,
        Object rawDefaultValue) {
    String value = null;
    CharSequence[] defaultValue;
    if (rawDefaultValue == null) {
        defaultValue = new CharSequence[0];
    } else {
        defaultValue = (CharSequence[]) rawDefaultValue;
    }
    List<CharSequence> joined = Arrays.asList(defaultValue);
    String joinedDefaultValue = join(joined, separator);
    if (restoreValue) {
        value = getPersistedString(joinedDefaultValue);
    } else {
        value = joinedDefaultValue;
    }

    setSummary(prepareSummary(Arrays.asList(unpack(value))));
    setValueAndEvent(value);
}

protected static String join(Iterable<?> iterable, String separator) {
    Iterator<?> oIter;
    if (iterable == null || (!(oIter = iterable.iterator()).hasNext()))
        return "";
    StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next()));
    while (oIter.hasNext())
        oBuilder.append(separator).append(oIter.next());
    return oBuilder.toString();
}

}

最佳答案

我相信您使用 this gist 中的代码除了分隔符之外,它的效果很好。我不知道为什么作者选择分隔符为“\u0001\u0007\u001D\u0007\u0001”

一旦我尝试将分隔符更改为任何其他字符串,例如 ",," 一切正常。

所选的分隔符字符串似乎会导致 Android 无法解析共享首选项 xml 文档。

关于java - Android ListPreference不保存选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24950070/

相关文章:

Android:复制/复制 SharedPreferences

android - 来自多个文件的 SharedPreferences

java - 尝试使用 Maven 和 WindowBuilder 运行 Java 应用程序时出现 "Unsatisfied Link"错误

java - 设置 "On start"fragment

android - 将 Android Activity 从一个应用程序复制到另一个应用程序

android - 防止 toast 消息在触摸时被取消

android - PreferenceManager.setDefaultValues readAgain 参数和新首选项

java - 将图像设置为 JFrame 的背景

java - 无法使用 ScalarDB 连接到我自己的 azure cosmos 数据库实例

android - 如何检索 Quickblox 自定义对象的相关记录?