0

My situation is that: I have a button that change background of my parent layout with a image of SD (this work fine). Then I like save these image in a SharedPreference to allow the user start my app with their background image, and not my default background image. I save the image this way:

                    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 ));

And I retrieve on this way (this code is in 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);
    }

Is the first time that use sharedpreferences and play with images in base64, so I'm little stuck with this, if I kill my app and restart, the default backgrounds appear, instead the custom. Any help? thanks and sorry for my english.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Genaut
  • 1,810
  • 2
  • 29
  • 60

1 Answers1

1

You forgot editor.commit() to actually save you string in Preferences.

Iulia Barbu
  • 1,522
  • 12
  • 25
  • Sure! Thanks a lot iulia :) I was thinking that the problem was big and hidden ;) – Genaut Jun 19 '12 at 11:12
  • 1
    consider using apply() http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply() instead, as it writes changes to file asynchronous – AZ13 Jun 19 '12 at 11:46
  • Thanks AZ13, apply save me once :) – Genaut Jul 22 '12 at 12:16