Home » Android » How to store images using SharedPreference in android?

How to store images using SharedPreference in android?

Posted by: admin April 23, 2020 Leave a comment


I want to save images in android using SharedPreference. I have two activity classes, when I click the button of the first activity it will call the second activity and the second activity displays my preferred name in a list view and also resets the android wallpaper to the image that I had set as a preferred wallpaper in the first activity.

For the second activity the code is:

public class PreferencesActivityTest extends PreferenceActivity {

    protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
            String prefName = myPrefs.getString("PREF_USERNAME", "nothing");
            String wallPaper = myPrefs.getString("PREFS_NAME", null);

            if(wallPaper != null) {

                try {

                      Bitmap bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
                      Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
                      Toast.makeText(this, "Wall paper has been changed." +
                                  "You may go to the home screen to view the same", Toast.LENGTH_LONG).show();

                catch (FileNotFoundException fe){
                      Log.e(getClass().getSimpleName(),"File not found");
                } catch (IOException ie) {
                      Log.e(getClass().getSimpleName()," IO Exception");


        ArrayList<String> results = new ArrayList<String>();
        results.add("Your Preferred name is: " + prefName);
      this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

The first activity calls the second activity but it is not calling if(wallPaper != null){}

Why isn’t it working?

How to&Answers:

Its not recommended to store image in Share preferences And you should store that image to sdcard.And then store image path (from sdcard) into Share preferences like this–

    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit=shre.edit();

and then fetch image from sdcard by using this path


All you have to do is, convert your image to it’s Base64 string representation:

Bitmap realImage = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);   
byte[] b = baos.toByteArray(); 

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();

and then, when retrieving, convert it back into bitmap:

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);

However, I have to tell you that Base64 support is only recently included in API8. To target on lower API version, you need to add it first. Luckily, this guy already have the needed tutorial.

Also, I’ve created quick and dirty example I publish on github.


Hey friends I got the solution of above problem.Here I post my full source code so that others can use this solution.

This is my second solution on this problem,Already I post one answer this is different answer for same question.
How to save Image in shared preference in Android | Shared preference issue in Android with Image.

Follow below steps:-

  1. Declare bitmap and String as static

    public static final String PRODUCT_PHOTO = "photo";
    public static Bitmap product_image;
  2. In onCreate() write some code.

    //---------set the image to bitmap
    product_image= BitmapFactory.decodeResource(getResources(), .drawable.logo);
    //____________convert image to string
    String str_bitmap = BitMapToString(product_image);
    //__________create two method setDefaults() andgetDefaults()
    setDefaults(PRODUCT_PHOTO, str_bitmap, this)  
    getDefaults(PRODUCT_PHOTO, this);
    1. write below code in methods


    public static void setDefaults(String str_key, String value, Context    context)
     SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor edit=shre.edit();
    edit.putString(str_key, value);


   public static String getDefaults(String key, Context context)
    SharedPreferences preferences =            PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);

  1. BitMapToString();

    public static String BitMapToString(Bitmap bitmap)
    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte[] arr = baos.toByteArray();
    return Base64.encodeToString(arr, Base64.DEFAULT);

    Now,If You want access this image file in another activity,follow below steps.

  2. Declare String as static

    public static final String PRODUCT_PHOTO = "photo";
    String str_bitmap;
    private  Bitmap bitmap;
    private ImageView  imageView_photo;

    In onCreate() :

      //--------get image form previous activity,here ProductActivity is my previous activity.
     str_bitmap =ProductActivity.getDefaults(PRODUCT_PHOTO, this);
     //-------------- decode the string to the bitmap
     //----------- finally set the this image to the Imageview.

for decodeBase64();

     public static Bitmap decodeBase64(String input)
     byte[] decodedByte = Base64.decode(input, 0);
     return BitmapFactory.decodeByteArray(decodedByte, 0,   decodedByte.length);