40

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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(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);
                      setWallpaper(bm);
                      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?

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Laxmipriya
  • 499
  • 1
  • 5
  • 9
  • Have you previously set a preference string called `"PREFS_NAME"` with a `SharedPreferences.Editor` (and made sure you called `commit()`? Why are you using `MODE_WORLD_READABLE`? Do you want to allow other applications to use your preference? – Martin Foot Dec 05 '11 at 13:40
  • yes,I have declared all these with my first activity class. still it is not working. – Laxmipriya Dec 06 '11 at 11:02
  • look at this solution https://stackoverflow.com/a/59501186/1844851 – VasanthRavichandran Dec 27 '19 at 13:03

3 Answers3

86

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);
textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

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);
    imageConvertResult.setImageBitmap(bitmap);
}

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 on github.

ariefbayu
  • 21,849
  • 12
  • 71
  • 92
  • 8
    Nice effort but the post is somewhat misleading. While it is what the OP seems to ask for, storing lots of data in SharedPreferences is not what they are designed for and this should be made more clear. While it is true that [it is possible to store fairly large amounts of data in them](http://stackoverflow.com/questions/6326171/is-using-android-shared-preferences-for-storing-large-amounts-of-data-a-good-ide), the docs state that you should 'Use Shared Preferences for primitive data'. A good overview can be found [here](http://developer.android.com/guide/topics/data/data-storage.html). – Martin Foot Dec 21 '11 at 09:25
  • 3
    @MartinFoot, I'm fully aware of that before answering this question. – ariefbayu Dec 21 '11 at 10:31
32

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();
    edit.putString("imagepath","/sdcard/imh.jpeg");
    edit.commit();

and then fetch image from sdcard by using this path

Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87
3

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

    setDefaults();

    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);
    edit.apply();
    }
    

3.2.setDefaults();

   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
     bitmap=decodeBase64(str_bitmap);
     //----------- finally set the this image to the Imageview.
     imageView_photo.setImageBitmap(bitmap);
    

for decodeBase64();

     public static Bitmap decodeBase64(String input)
     {
     byte[] decodedByte = Base64.decode(input, 0);
     return BitmapFactory.decodeByteArray(decodedByte, 0,   decodedByte.length);
     }
Community
  • 1
  • 1
sachin pangare
  • 1,527
  • 15
  • 11