I want to store the bitmap object in shared preferences and on resume method just retrieve that object and set it in background.Please tell me how to store and retrieve it form shared preferences.The problem is that in shared preferences we can put the values like String,int,bolean,long etc but not the bitmao object.Please help me to sort out this problem.Below is my code:
@Override
protected void onResume() {
super.onResume();
rl_changeBackground.setBackgroundDrawable(new BitmapDrawable(getResources(),HomeSafeStaticVariables.bitmap));
}
}
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(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
This may help you. Try and please let me know !
you can store Bitmap as base64 string in SharedPreferences
.But it is not good practice to store bitmap images in SharedPreferences
. you should store the image in the SD card and save the path in the SharedPreferences
.
Check this question
If you really want to store your image into SharedPreferences you should have a look at this solution (or similar that already exist here):
How to store and retrieve bitmap in sharedPreferences in Android?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With