0

I have an Activity on my app that has to save some data, and that data has to be accesed from other Activity, so i´m using SharedPreferences to do this, the problem is that, when i try to save the bitmap of an ImageView with:

ImageButton imgView = (ImageButton) findViewById(R.id.UserImageButton);
Bitmap bitmap = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
editor.putInt("bitmap", bitmap);

Or directly with:

ImageButton imgView = (ImageButton) findViewById(R.id.UserImageButton);;
editor.putInt("bitmap", ((BitmapDrawable)imgView.getDrawable()).getBitmap());

But it doesn´t work. How can I save it?? Thanks a lot

Javierd98
  • 708
  • 9
  • 27

2 Answers2

0

You can add only Boolean, Float, Int, Long, String values in SharedPreference. But one thing you can do is converting Bitmap to Base64 String. And after retrieving it from SharedPrefrence convert it to Bitmap.

Use following method to convert bitmap to byte array:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(b, Base64.DEFAULT); 
And Save it to SharedPrefrence.

Now assuming that your image data is in a String called encoded , the following should do give you BitMap from Base64 string:

byte[] imageAsBytes = Base64.decode(encoded.getBytes());
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

:)

  • No, don't do this, it's completely unnecessary to convert a Bitmap to a String just to store it in SharedPreferences and then convert it back to display it. – Karakuri Nov 13 '16 at 21:37
-1

The is no reason to store an entire Bitmap in SharedPreferences. Save it as an ordinary file. If you have to store anything in SharedPreferences, just store the file path.

Karakuri
  • 38,365
  • 12
  • 84
  • 104