How to save Image in shared preference in Android | Shared preference issue in Android with Image

前端 未结 4 650
难免孤独
难免孤独 2020-11-27 17:34

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 s

4条回答
  •  猫巷女王i
    2020-11-27 17:57

    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.

提交回复
热议问题