14

In my application after login I have to save user name and image in shared preference for other pages. I am able to save name in preference but can't get any where how to save image.

I am trying something like that-

SharedPreferences myPrefrence;
    String namePreferance="name";

    String imagePreferance="image";

SharedPreferences.Editor editor = myPrefrence.edit();
                editor.putString("namePreferance", itemNAme);
                editor.putString("imagePreferance", itemImagePreferance);
                editor.commit();

I am trying to save image as string after convert it into object. But when I reconvert it into bitmap I did not get anything.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Why would you store it in the SharedPreferences? That is not the correct location for storing images. You should cache them on the external storage if one is available and if not then you should try to store them on the internal storage but watch out when working with the internal storage as you generally won't have as much space as on the external storage. Check out this [link](http://developer.android.com/guide/topics/data/data-storage.html#filesExternal) on using the external storage. – Chetna Aug 06 '13 at 05:37
  • @Chetna Thanks but I am confused, what's happen when user change profile image or he/she login with another account? –  Aug 06 '13 at 05:39
  • Did you try to google your problem? Because if you had, you would have found a solution. [This](http://stackoverflow.com/questions/8586242/how-can-i-store-images-using-sharedpreference-in-android) is one of them. – Chetna Aug 06 '13 at 05:44
  • @Chetna yes I google a lot and also try on stackoverflow and i have already spent 2 days, only after that i put my question here. This is some tough to other also you can see no answer still on my question. –  Aug 06 '13 at 05:46
  • Check http://stackoverflow.com/a/8586243/1081355 . I think this is the solution to your problem. – Chetna Aug 06 '13 at 05:48
  • Thanks, I think better option is convert it into base64 as a string and store in preference right? –  Aug 06 '13 at 05:51
  • I have one more open question no one response on it can you give me any suggestion on it? http://stackoverflow.com/questions/18056839/issue-in-inner-join-query-in-android-trouble-in-sqlite-query –  Aug 06 '13 at 05:54
  • I think better option is to save the path, as the images are too heavy to be saved in shared preference. But it all depends on your needs. – Chetna Aug 06 '13 at 05:59
  • Thanks! I will inform you if got any trouble.. Thanks for your kind help! –  Aug 06 '13 at 06:20
  • Look at this solution, it's worked for me https://stackoverflow.com/a/59501186/1844851 – VasanthRavichandran Dec 27 '19 at 13:02

4 Answers4

56

I solved your problem do something like that:

  1. Write Method to encode your bitmap into string base64-

    // method for bitmap to base64
    public static String encodeTobase64(Bitmap image) {
        Bitmap immage = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    
        Log.d("Image Log:", imageEncoded);
        return imageEncoded;
    }
    
  2. Pass your bitmap inside this method like something in your preference:

    SharedPreferences.Editor editor = myPrefrence.edit();
    editor.putString("namePreferance", itemNAme);
    editor.putString("imagePreferance", encodeTobase64(yourbitmap));
    editor.commit();
    
  3. And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:

    // method for base64 to bitmap
    public static Bitmap decodeBase64(String input) {
        byte[] decodedByte = Base64.decode(input, 0);
        return BitmapFactory
                .decodeByteArray(decodedByte, 0, decodedByte.length);
    }
    
  4. Please pass your string inside this method and do what you want.

honk
  • 9,137
  • 11
  • 75
  • 83
Manish Srivastava
  • 1,649
  • 2
  • 15
  • 23
  • 1
    Hi Manish first thanks for your response! I have already solve my problem with the help of chetna.. Thanks for your time and line by line explanation .. Hope in future it will help some one else so I am giving you up vote.. –  Aug 07 '13 at 04:44
  • Nice Work Keep it up! –  Aug 07 '13 at 04:46
  • Because of less point i am unable to up vote you. Can you give me some point please? –  Aug 07 '13 at 04:48
  • How did you get the name of the image? When you put it in the sharedPref. – RoCkDevstack Jun 14 '16 at 12:41
  • Do you retain the image quality when you do this? – portfoliobuilder Sep 09 '16 at 05:32
6
Finally I solved this problem.

Step:- 1. I wrote some code in onCreate() for get intent data from previous Activity

 private  Bitmap bitmap;

 Intent intent = getIntent();

        if (getIntent().getExtras() != null)
        {
            // for get data from intent

            bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");

            // for set this picture to imageview

            your_imageView.setImageBitmap(bitmap);

             sharedPreferences();

        }else
        {
            retrivesharedPreferences();
        }

2 create sharedPreferences() and put this code

 private void sharedPreferences()
    {
        SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
        editor.commit();
    }

3 create retrivesharedPreferences() this method and put this code,

private void retrivesharedPreferences()
    {
      SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
        String photo = shared.getString("PRODUCT_PHOTO", "photo");
        assert photo != null;
        if(!photo.equals("photo"))
        {
            byte[] b = Base64.decode(photo, Base64.DEFAULT);
            InputStream is = new ByteArrayInputStream(b);
            bitmap = BitmapFactory.decodeStream(is);
            your_imageview.setImageBitmap(bitmap);
        }

    }

4 Write encodeTobase64() Method to encode your bitmap into string base64- and put code in this method

 public static String encodeTobase64(Bitmap image) {
        Bitmap bitmap_image = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

        return imageEncoded;
    }

I hope it will helpful for you.

sachin pangare
  • 1,527
  • 15
  • 11
4

Encode to Base64?! That's crazy talk! That's way too much information that you are storing to the shared preferences. The strategy you should be doing is saving the Image URI file path, and retrieving it as such. This way, your app won't be storing so much information and become a memory hog when decoding the image.

I made a simple App on Github to demonstrate this idea, if you want to follow:

1. Declare the variables:

private ImageView mImage;
private Uri mImageUri;

2. Select the image:

public void imageSelect() {
     Intent intent;
     if (Build.VERSION.SDK_INT < 19) {
         intent = new Intent(Intent.ACTION_GET_CONTENT);
     } else {
         intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
         intent.addCategory(Intent.CATEGORY_OPENABLE);
     }
     intent.setType("image/*");
     startActivityForResult(Intent.createChooser(intent, "Select Picture"),
         PICK_IMAGE_REQUEST);
 }

3. Save the image URI:

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     // Check which request we're responding to
     if (requestCode == PICK_IMAGE_REQUEST) {
         // Make sure the request was successful
         if (resultCode == RESULT_OK) {
             // The user picked a image.
             // The Intent's data Uri identifies which item was selected.
            if (data != null) {

                // This is the key line item, URI specifies the name of the data
                mImageUri = data.getData();

                // Removes Uri Permission so that when you restart the device, it will be allowed to reload. 
                this.grantUriPermission(this.getPackageName(), mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                this.getContentResolver().takePersistableUriPermission(mImageUri, takeFlags);

                // Saves image URI as string to Default Shared Preferences
                SharedPreferences preferences = 
                     PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("image", String.valueOf(mImageUri));
                editor.commit();

                // Sets the ImageView with the Image URI
                mImage.setImageURI(mImageUri);
                mImage.invalidate();
             }
         }
     }
 }

4. Retrieve the image URI when needed:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mImageUri = preferences.getString("image", null);
mImage.setImageURI(Uri.parse(mImageUri));

That's it! Now we have saved the image uri path to shared preferences cleanly, and have not wasted valuable system resources encoding the image and saving it to SharedPreferences.

Martin Sing
  • 1,247
  • 10
  • 15
0
//Thanks Maish srivastava 
// i will do complete code just copy past and run it sure worked it
//
public class MainActivity extends Activity  implements OnClickListener
{
    private static int RESULT_LOAD_IMAGE = 1;
    public static final String MyPREFERENCES = "MyPre" ;//file name
       public static final String  key = "nameKey"; 
       SharedPreferences sharedpreferences ;
       Bitmap btmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         sharedpreferences =  getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
         if (sharedpreferences.contains(key))
          {
                String u=sharedpreferences.getString(key, "");
                btmap=decodeBase64(u); 
                ImageView iv = (ImageView) findViewById(R.id.imageView1);
                iv.setImageBitmap(btmap);
          }
       ImageButton imgbtn=(ImageButton) findViewById(R.id.imageButton1);
       imgbtn.setOnClickListener(this);
    }

public void onClick(View  v) 
{
    // TODO Auto-generated method stub
    switch (v.getId())
     {
             case R.id.imageButton1: 
                  try 
                  { //go to image library and pick the image
                   Intent i=newIntent(ntent.ACTION_PICK,
                   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                   startActivityForResult(i, RESULT_LOAD_IMAGE);      
                  } 
                  catch (Exception e) 
                  {
                   e.printStackTrace();
                  }
                  break;
     }  
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
    {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        btmap=BitmapFactory.decodeFile(picturePath);//decode method called

        Editor editor = sharedpreferences.edit();
        editor.putString(key,  encodeTobase64(btmap));
        editor.commit();   
    }


}
public static String encodeTobase64(Bitmap image)
     {
    Bitmap immage = image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.d("Image Log:", imageEncoded);
    return imageEncoded;

     }
public static Bitmap decodeBase64(String input) 
{
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory
            .decodeByteArray(decodedByte, 0, decodedByte.length);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
sandhu
  • 305
  • 4
  • 4