执行了 OnActivityResult Fragment 中的方法,但在 View 中什么也没发生

时间:2021-03-03 09:07:07

标签: android kotlin android-fragments android-camera imagepicker

你能帮我吗?,? 我是开发 Android 使用 kotlin 的新手,还在学习中。,

这是我在 Fragment 上的代码。,

......
  private fun takePhotoFromCamera() {

        Dexter.withActivity(requireActivity())
            .withPermissions(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            )
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
                    // Here after all the permission are granted launch the CAMERA to capture an image.
                    if (report!!.areAllPermissionsGranted()) {
                        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                        intent.putExtra("Document", 2)
                        startActivityForResult(intent, CAMERA)
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    permissions: MutableList<PermissionRequest>?,
                    token: PermissionToken?,
                ) {
                    showRationalDialogForPermissions()
                }
            }).onSameThread()
            .check()
    }

    private fun choosePhotoFromGallery() {
        Dexter.withActivity(activity)
            .withPermissions(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(report: MultiplePermissionsReport?) {

                    // Here after all the permission are granted launch the gallery to select and image.
                    if (report!!.areAllPermissionsGranted()) {

                        val galleryIntent = Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                        )
                     galleryIntent.putExtra("Document", 2)
                     startActivityForResult(galleryIntent, GALLERY)
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    permissions: MutableList<PermissionRequest>?,
                    token: PermissionToken?,
                ) {
                    showRationalDialogForPermissions()
                }
            }).onSameThread()
            .check()
    }

和这个 onActivityResult 来自父 ActivityFragment

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        for (fragment in supportFragmentManager.fragments) {
            fragment.onActivityResult(requestCode, resultCode, data)
        }
    }

还有这个 OnActivityResult 来自 Fragment

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == GALLERY) {
            if (data != null) {
                val contentURI = data.data
                try {
                    // Here this is used to get an bitmap from URI
                    @Suppress("DEPRECATION")
                    val selectedImageBitmap =
                        MediaStore.Images.Media.getBitmap(requireActivity().contentResolver,
                            contentURI)

                    // TODO (Step 3 : Saving an image which is selected from GALLERY. And printed the path in logcat.)
                    // START
                    val saveImageToInternalStorage =
                        saveImageToInternalStorage(selectedImageBitmap)
                    Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
                    // END
                    binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
                    binding.ivPvNpwp.foreground.clearColorFilter()
                    binding.cvNpwp.visibility=View.GONE
                    binding.btnCaptureNpwp.visibility=View.GONE
                    binding.ivNpwpPreview.setImageBitmap(selectedImageBitmap) // Set the selected image from GALLERY to imageView.
                } catch (e: IOException) {
                    e.printStackTrace()
                    Toast.makeText(requireActivity(), "Failed!", Toast.LENGTH_SHORT).show()
                }
            }
        } else if (requestCode == CAMERA) {

            val thumbnail: Bitmap = data!!.extras!!.get("data") as Bitmap // Bitmap from camera

            // TODO (Step 4 : Saving an image which is selected from CAMERA. And printed the path in logcat.)
            // START
            val saveImageToInternalStorage =
                saveImageToInternalStorage(thumbnail)
            Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
            //binding.btnCaptureKtp.text = getString(R.string.regist_step_2_KTP_retake).toString()
            // END
            binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
            binding.ivPvNpwp.foreground.clearColorFilter()
            binding.btnCaptureNpwp.visibility=View.GONE
            binding.cvNpwp.visibility=View.GONE
            binding.ivNpwpPreview.setImageBitmap(thumbnail) // Set to the imageView.
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        Log.e("Cancelled", "Cancelled")
    }
    //
}

我的问题是为什么这个块被执行了,但什么也没发生??

 ....
binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
        binding.ivPvNpwp.foreground.clearColorFilter()
        binding.btnCaptureNpwp.visibility=View.GONE
        binding.cvNpwp.visibility=View.GONE
        binding.ivNpwpPreview.setImageBitmap(thumbnail)
......

感谢您回答我的问题。

2 个答案:

答案 0 :(得分:0)

尝试对“contentURI”进行另一个空检查。喜欢:-

if(contentURI != null){

        try {
            // Here this is used to get an bitmap from URI
            @Suppress("DEPRECATION")
            val selectedImageBitmap =
                MediaStore.Images.Media.getBitmap(requireActivity().contentResolver,
                    contentURI)

            // TODO (Step 3 : Saving an image which is selected from GALLERY. And printed the path in logcat.)
            // START
            val saveImageToInternalStorage =
                saveImageToInternalStorage(selectedImageBitmap)
            Log.i("Saved Image : ", "Path :: $saveImageToInternalStorage")
            // END
            binding.btnNpwpCaptureAgain.visibility=View.VISIBLE
            binding.ivPvNpwp.foreground.clearColorFilter()
            binding.cvNpwp.visibility=View.GONE
            binding.btnCaptureNpwp.visibility=View.GONE
            binding.ivNpwpPreview.setImageBitmap(selectedImageBitmap) // Set the selected image from GALLERY to imageView.
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(requireActivity(), "Failed!", Toast.LENGTH_SHORT).show()
        }
    }

由于 onActivityResult() 方法已被弃用,最好使用 registerForActivityResult()。如下图:

    private val startForResultToLoadImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        try {
            val selectedImage: Uri? = result.data?.data
            if (selectedImage != null){
                 // From Gallery
                 // Use uri to get the image

            }else{
                  // From Camera code goes here.
                  // Get the bitmap directly from camera
                val bitmap: Bitmap = result.data?.extras?.get("data") Bitmap
            }
        } catch (error: Exception) {
            Log.d("log==>>", "Error : ${error.localizedMessage}")
        }
    }
}

对于画廊来说:

val intent = Intent (Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI) 

startForResultToLoadImage.launch(intent)

对于相机来说,像这样调用:

val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, it)
startForResultToLoadImage.launch(intent)

答案 1 :(得分:0)

我相信你应该:

  1. 在函数开始时打印日志并打印所有参数,以便始终知道代码将如何分支。类似于 Log.i("onActivityResult: ", "requestCode=" + requestCode + “, resultCode=” + resultCode + “, data=” + data);
  2. 在检查结果代码之前检查您的请求代码,因为不同的请求可能有不同的结果。
  3. 您假设结果是 Activity.RESULT_CANCELEDActivity.RESULT_OK,但结果代码可能是自定义结果,因此请在选中 {{1} 后添加另一个 else 分支} 以确保您涵盖所有结果。
  4. 如果您的 Activity 继承自 Activity.RESULT_CANCELED,请勿从 Fragment.onActivityResult 调用 Activity.onActivityResult。 Activity 自动将结果转发到片段(它甚至允许跨片段的请求代码重复,而不会混合片段)。

AppCompatActivity 的结构应该主要是:

onActivityResult

我会用 switch-case 代替 if-else,但这是你的代码风格,所以我不会判断:)

相关问题