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

前端 未结 4 634
难免孤独
难免孤独 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条回答
  • 2020-11-27 17:36
    //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;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 17:56

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 17:58

    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.

    0 讨论(0)
提交回复
热议问题