'Android - Save my image To Gallery / External Storage in Android Studio

I am making a framer app which can be used to frame your image. And i Want to save that image in gallery after framing and for this i have set a button to perform this but in the button by below code i am unable to save my image. After clicking on button it crashes the app activity. please Someone Give me Solution. I am using api level >29.

```  dlbtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

           OutputStream outputStream;

           BitmapDrawable drawable = (BitmapDrawable) mainimg.getDrawable();
           Bitmap bitmap = drawable.getBitmap();

           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
           {
               ContentResolver resolver = MainActivity2.this.getContentResolver();
               ContentValues contentValues = new ContentValues();
               contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME,"Image_"+".jpg");
               contentValues.put(MediaStore.MediaColumns.MIME_TYPE,"image/jpeg");
               contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_PICTURES + File.separator+"TestFolder");
               Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
               try {
                   outputStream =  resolver.openOutputStream(Objects.requireNonNull(imageUri) );
                   bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                   Objects.requireNonNull(outputStream);
                   Toast.makeText(MainActivity2.this, "Image Saved", Toast.LENGTH_SHORT).show();

               } catch (Exception e) {
                   Toast.makeText(MainActivity2.this, "Image Not Not  Saved: \n "+e, Toast.LENGTH_SHORT).show();

                   e.printStackTrace();
               }

           }


       }
   });

} ``


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source