Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store bitmap object in sharedpreferences in android [duplicate]

Tags:

android

bitmap

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

    }
    }
like image 711
Deepak Sharma Avatar asked Jun 24 '13 05:06

Deepak Sharma


3 Answers

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 !

like image 175
Akhilesh Mani Avatar answered Oct 23 '22 04:10

Akhilesh Mani


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

like image 3
null pointer Avatar answered Oct 23 '22 06:10

null pointer


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?

like image 1
Marek Avatar answered Oct 23 '22 04:10

Marek