Home > Net >  Save image in gallery in android
Save image in gallery in android

Time:06-13

Asks: How to pass an image URL to intent when updating compile-SDK? When I update compile-SDK to Version 30. This message appears in Android Studio. And the app crashes. but when I downgrade it to a lower version, for example, 29, the application works very well.

I tried a lot to solve it, but unfortunately, it did not work ... can You help me.

FilterCollageActivity
    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.img_save -> {
                checkClick()
                isFromSaved = true
                try {
                    saveBitmap(screenShot)
                } catch (th: Throwable) {
                    th.printStackTrace()
                }
                val intent = Intent(this, ShowImageActivity::class.java)
                intent.putExtra("image_uri", savedImageUri!!.toString())
                startActivityForResult(intent, 2)
                finish()
            }
        }
    }

ShowImageActivity

    class ShowImageActivity : AppCompatActivity(), View.OnClickListener {
    
        private var image_uri: String? = null
        private var img_show: ImageView? = null
        private var saved_file: File? = null
        private var density: Float = 0.toFloat()
        internal var D_height: Int = 0
        internal var D_width: Int = 0
        private var display: DisplayMetrics? = null
    
        private var mLastClickTime: Long = 0
        fun checkClick() {
            if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                return
            }
            mLastClickTime = SystemClock.elapsedRealtime()
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
            setContentView(R.layout.activity_show_image)
    
            image_uri = intent.getStringExtra("image_uri")
            saved_file = File(image_uri!!)
            img_show = findViewById<View>(R.id.img_show) as ImageView
    
            display = resources.displayMetrics
            density = resources.displayMetrics.density
            D_width = display!!.widthPixels
            D_height = (display!!.heightPixels.toFloat() - density * 150.0f).toInt()
    
            val layoutParams = RelativeLayout.LayoutParams(D_width, ViewGroup.LayoutParams.WRAP_CONTENT)
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
            img_show!!.layoutParams = layoutParams
    
            img_show!!.setImageURI(Uri.parse(image_uri))
    
    ...
    
    
        }

2022-06-13 15:47:38.495 20691-20691/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.cocnanvd.nvdframe, PID: 20691
    java.lang.NullPointerException
        at com.cocnanvd.nvdframe.FilterCollageActivity.onClick(FilterCollageActivity.kt:53)
        at android.view.View.performClick(View.java:8160)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8653)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

CodePudding user response:

after api level 30, maybe your saveBitmap() method not work so hare intent.putExtra("image_uri", savedImageUri!!.toString()) you got a null pointer exception. may be other reasons as well like write permission etc . please add full FilterCollageActivity code

CodePudding user response:

Here is the solution.

Step : 1

private fun checkPermissionAndProceed() {
        val permission: Collection<String> =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) arrayListOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_MEDIA_LOCATION
            ) else arrayListOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )

        Dexter.withContext(this@SolutionActivity)
            .withPermissions(permission)
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(multiplePermissionsReport: MultiplePermissionsReport) {
                    if (multiplePermissionsReport.areAllPermissionsGranted()) {
                        addImageToGallery(
                            "IMG_"   System.currentTimeMillis()   ".JPEG",
                            bitMap!!, this@SolutionActivity
                        )
                    }

                    if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied) {
                        //showSettingsDialog()
                        //Tell user why you need this permission.
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    list: List<PermissionRequest>,
                    permissionToken: PermissionToken
                ) {
                    permissionToken.continuePermissionRequest()
                }
            }).onSameThread().check()
    }

Step : 2

private fun addImageToGallery(fileName: String, bitmap: Bitmap, ctx: Context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

                val fos: OutputStream
                val resolver = contentResolver
                val values = ContentValues()

                values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
                values.put(
                    MediaStore.MediaColumns.RELATIVE_PATH,
                    Environment.DIRECTORY_PICTURES   File.separator   "MyImages"
                )

                val imageUri = resolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values
                )
                fos = resolver.openOutputStream(imageUri!!) as OutputStream
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.close()
                Toast.makeText(ctx, getString(R.string.saved_in_gallery), Toast.LENGTH_SHORT).show()

            } else {
                val values = ContentValues()
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.Images.ImageColumns.TITLE, fileName)

                val uri: Uri? = ctx.contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values
                )
                uri?.let {
                    ctx.contentResolver.openOutputStream(uri)?.let { stream ->
                        val oStream = BufferedOutputStream(stream)
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
                        oStream.close()
                        Toast.makeText(
                            ctx, getString(R.string.saved_in_gallery), Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        } catch (e: Exception) {
            Toast.makeText(ctx, e.localizedMessage, Toast.LENGTH_SHORT).show()
        }
    }
  • Related