Android偏好添加不需要的字符

时间:2015-12-26 13:57:24

标签: android android-preferences android-sharedpreferences

Android中的SharedPreferences存在很大问题。一旦应用程序关闭,首选项就会向我的一个字符串值添加不需要的字符。实际上它是一个可配置的转义序列。

我有一个简单的设置,MainActivity包含

@Override
protected void onStart() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sequence = prefs.getString("escape_sequence", "");
}

设置值的首选项屏幕。当我打开应用程序进入prefences屏幕时,将值正确设置为\n\n并返回MainActivity断点正确显示序列为Java.lang.String, value(char[2])= "\n\n", count=2。当我现在通过android studio重新启动应用程序时,代码中的相同断点突然显示:Java.lang.String, value(char[6])= "\n\n ", count=6,包含4个空格和10个转义\u0000个字符。

任何人都可以为什么会这样,我能做些什么呢?

顺便说一下,到目前为止,我还没有触及App中任何地方的SharedPreferences.Editor。我是通过PreferencesScreen严格完成的。因此,在应用程序的任何位置都不会进行覆盖。也不应该应用默认值,但无论如何设置为android:defaultValue="\n\n"

修改

我找到了原因:如果换行符位于首选项的末尾,则android会添加空格。我不明白为什么。

修改

以下是自定义偏好设置代码:

public class SequencePreference extends DialogPreference {
    EditText sequenceInput;

    public SequencePreference(Context context, AttributeSet attrs) {
        super(context, attrs);

        setDialogLayoutResource(R.layout.dialog_preference_sequence);
        setPositiveButtonText(R.string.settings_sequence_ok);
        setNegativeButtonText(R.string.settings_sequence_cancel);

        setDialogIcon(null);
    }

    @Override
    protected View onCreateDialogView() {
        View view = super.onCreateDialogView();
        sequenceInput= (EditText)view.findViewById(R.id.sequence_input);

        return view;
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        // When the user selects "OK", persist the new value
        if (positiveResult) {
            String sequenceValue = new String( sequenceInput.getText().toString() );

            String[] parts = sequenceValue.split("-");
            if(parts.length == 2) {
                persistString(parts[1]);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:7)

我认为这是Android API 18和更新版本中的一个错误,当SharedPreferences字符串以\n结尾时会注入额外的空格。有关更多信息,请参阅:

https://code.google.com/p/android/issues/detail?id=159799#c6 https://code.google.com/p/android/issues/detail?id=159799#c7

答案 1 :(得分:0)

检索保存的字符串后,放置trim()。 例子

String sequence2 = sequence.trim()