Android:回车保存到SharePreference异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/murphykwu/article/details/84392193

背景

在项目中发现,当通过SharePreference保存一个回车。如果重新安装应用,这个回车读出来的值就改变了。

分析

通过读取保存时候的EditText里面的String值,通过toCharArray转换成char数组,打印每个数组的ascii码。发现输出是10,10.也就是回车对应的ascii码。
重新安装应用,从SharePreference里面读取保存的回车值,再次打印char数组,发现该数组为:10,32,10,32,32. 跟视觉上的异常情况类似。
怀疑是char值转换成String的时候出现异常。

解决方法

不使用SharePreference来保存特殊字符,而是采用读写文件的方式。经过验证,解决该问题。在onPause的时候writeFile,然后在onCreate的时候readFile并且设置到EditText中即可。多个数值之间用冒号分隔。
代码如下:

private void writeFile()
{
    try {
        FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
        CharSequence prefix = mPrefix.getText();//mPrefix和mSuffix为EditText
        CharSequence suffix = mSuffix.getText();
        String writeResult = prefix+":"+suffix;
        fos.write(writeResult.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void readFile(){
    String result = "";
    try {
        FileInputStream fis = openFileInput(FILE_NAME);
        int len = fis.available();
        if(len <= 0)
        {
            return;
        }
        byte[] buffer = new byte[len];
        fis.read(buffer);
        result = new String(buffer, "UTF-8");
        String[] split = result.split(":");
        sPrefix = split[0];
        sSuffix = split[1];
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/murphykwu/article/details/84392193