Android Camera : data intent returns null

前端 未结 11 1601
不知归路
不知归路 2020-11-22 16:20

I have an android application which contains multiple activities.

In one of them I\'m using a button which will call the device camera :

public void         


        
11条回答
  •  悲哀的现实
    2020-11-22 17:07

    After much try and study, I was able to figure it out. First, the variable data from Intent will always be null so, therefore, checking for !null will crash your app so long you are passing a URI to startActivityForResult.Follow the example below. I will be using Kotlin.

    1. Open the camera intent

      fun addBathroomPhoto(){
      addbathroomphoto.setOnClickListener{
      
          request_capture_image=2
      
          var takePictureIntent:Intent?
          takePictureIntent =Intent(MediaStore.ACTION_IMAGE_CAPTURE)
          if(takePictureIntent.resolveActivity(activity?.getPackageManager()) != null){
      
              val photoFile: File? = try {
                  createImageFile()
              } catch (ex: IOException) {
                  // Error occurred while creating the File
      
                  null
              }
      
              if (photoFile != null) {
                  val photoURI: Uri = FileProvider.getUriForFile(
                      activity!!,
                      "ogavenue.ng.hotelroomkeeping.fileprovider",photoFile)
                  takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                      photoURI);
                  startActivityForResult(takePictureIntent,
                      request_capture_image);
              }
      
      
          }
      
      }
      

      }`

    2. Create the createImageFile().But you MUST make the imageFilePath variable global. Example on how to create it is on Android official documentation and pretty straightforward

    3. Get Intent

       override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      
      if (requestCode == 1 && resultCode == RESULT_OK) {
          add_room_photo_txt.text=""
          var myBitmap=BitmapFactory.decodeFile(imageFilePath)
          addroomphoto.setImageBitmap(myBitmap)
          var file=File(imageFilePath)
          var fis=FileInputStream(file)
          var bm = BitmapFactory.decodeStream(fis);
          roomphoto=getBytesFromBitmap(bm) }}
      
    4. The getBytesFromBitmap method

        fun getBytesFromBitmap(bitmap:Bitmap):ByteArray{
      
        var stream=ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
        }
      

    I hope this helps.

提交回复
热议问题