从共享偏好中检索已编码的位图

时间:2012-06-19 10:48:41

标签: android bitmap base64 preferences shared

我的情况是:我有一个按钮,用SD的图像改变我的父布局的背景(这很好)。然后我喜欢在SharedPreference中保存这些图像,以允许用户使用他们的背景图像启动我的应用程序,而不是我的默认背景图像。我用这种方式保存图像:

                    SharedPreferences.Editor editor = prefs.edit();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
                byte[] b = baos.toByteArray();
                editor.putString("background", Base64.encodeToString(b, Base64.DEFAULT ));

我以这种方式检索(此代码在onCreate中):

        prefs = getSharedPreferences("Mis preferencias",Context.MODE_PRIVATE);
    String fondo = prefs.getString("background", "vacio");

    if(!fondo.equals("vacio")){ 
        byte[] b = Base64.decode(fondo, Base64.DEFAULT);
        InputStream is = new ByteArrayInputStream(b);
        Bitmap yourSelectedImage = BitmapFactory.decodeStream(is);
        BitmapDrawable bd = new BitmapDrawable(getResources(), yourSelectedImage);
        View view = findViewById(R.id.padre);
        view.setBackgroundDrawable(bd);
    }

第一次使用共享偏好并在base64中播放图像,所以我很难坚持这一点,如果我杀了我的应用并重新启动,则显示默认背景,而不是自定义。有帮助吗?谢谢,抱歉我的英语。

1 个答案:

答案 0 :(得分:1)

您忘记editor.commit()在“偏好设置”中实际保存字符串。