Android Camera : data intent returns null

前端 未结 11 1586
不知归路
不知归路 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:03

    To Access the Camera and take pictures and set ImageView on Android

    You have to use Uri file = Uri.fromFile(getOutputMediaFile()); for marshmallow.

    Use below link to get path

    https://androidkennel.org/android-camera-access-tutorial/

    0 讨论(0)
  • 2020-11-22 17:05

    The following code works for me:

    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, 2);
    

    And here is the result:

    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
    { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
        if(resultCode == RESULT_OK)
        {
            Uri selectedImage = imageReturnedIntent.getData();
            ImageView photo = (ImageView) findViewById(R.id.add_contact_label_photo);
            Bitmap mBitmap = null;
            try
            {
                mBitmap = Media.getBitmap(this.getContentResolver(), selectedImage);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 17:08

    When we will capture the image from Camera in android then Uri or data.getdata() comes null. we have two solutions to resolve this issue.

    1. We can got the Uri path from the Bitmap Image
    2. We can got the Uri path from cursor.

    I will implement all methods here, Please carefully watch and read these:-

    First i will tell how to get Uri from Bitmap Image: Complete code is :

    First we will capture image through Intent that will same for both methods so this code i will write one time only here :

    // Capture Image
    captureImg.setOnClickListener(new View.OnClickListener(){
        @Override public void onClick(View view){
            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(intent.resolveActivity(getPackageManager())!=null){
                startActivityForResult(intent,reqcode);
            }
    
        }
    });  
    

    Now we will Implement OnActivityResult :-(This will be same for both above 2 methods):-

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == reqcode && resultCode == RESULT_OK)
        {
    
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView.setImageBitmap(photo);
    
            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
    
            //Show Uri path based on Image
            Toast.makeText(LiveImage.this, "Here " + tempUri, Toast.LENGTH_LONG).show();
    
            //Show Uri path based on Cursor Content Resolver
            Toast.makeText(this, "Real path for URI : " + getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
        }
    }     
    

    Now we will create all above method to create Uri from Image and Cursor methods via classes:

    Now URI path from Bitmap Image

    private Uri getImageUri(Context applicationContext, Bitmap photo)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
        return Uri.parse(path);
    }
    

    \ Uri from Real path of saved image

    public String getRealPathFromURI(Uri uri)
    {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }
    
    0 讨论(0)
  • 2020-11-22 17:09

    The default Android camera application returns a non-null intent only when passing back a thumbnail in the returned Intent. If you pass EXTRA_OUTPUT with a URI to write to, it will return a null intent and the picture is in the URI that you passed in.

    You can verify this by looking at the camera app's source code on GitHub:

    • https://github.com/android/platform_packages_apps_camera/blob/gingerbread-release/src/com/android/camera/Camera.java#L1186

      Bundle newExtras = new Bundle();
      if (mCropValue.equals("circle")) {
          newExtras.putString("circleCrop", "true");
      }
      if (mSaveUri != null) {
          newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
      } else {
          newExtras.putBoolean("return-data", true);
      }
      

    I would guess that you're either passing in EXTRA_OUTPUT somehow, or the camera app on your phone works differently.

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