-->

Getting Uri Null in capture photo from camera inte

2020-02-29 12:10发布

问题:

I am getting null in contenturi in samsung phones while capturing photo from camera but rest of others phones its working fine.

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {     
        super.onActivityResult(requestCode, resultCode, data);    
        try
        {
             if (requestCode == IMAGE_CAPTURE) {
                if (resultCode == RESULT_OK){

                    Uri contentUri = data.getData();
                    if(contentUri!=null)
                    {
                        String[] proj = { MediaStore.Images.Media.DATA };         
                        Cursor cursor = managedQuery(contentUri, proj, null, null, null);         
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);         
                        cursor.moveToFirst();         
                        imageUri = Uri.parse(cursor.getString(column_index));
                    }

                    tempBitmap = (Bitmap) data.getExtras().get("data"); 
                    mainImageView.setImageBitmap(tempBitmap);
                    isCaptureFromCamera = true;
                }
            }

回答1:

This above code works in some mobile but does not work in samsung mobile in my case, so I implemented the common logic for all devices.

After capturing the photo from camera, I implement a logic using Cursor and iterate the cursor to get the path of last captured photo from camera.The below code works fine on any device.

Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
    do {
        uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
        photoPath = uri.toString();
    }while(cursor.moveToNext());
    cursor.close();
}


回答2:

Hi i am also facing this issue to like I am checking app on MOTO G its not working but on Samsung devices its working So i do Below coding please check:-

Uri selectedImageUri = data.getData();

                try {
                    selectedImagePath = getPathBelowOs(selectedImageUri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (selectedImagePath == null) {
                    try {
                        selectedImagePath = getPathUpperOs(selectedImageUri);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


public String getPathBelowOs(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

/**
 * Getting image from Uri
 * 
 * @param contentUri
 * @return
 */
public String getPathUpperOs(Uri contentUri) {// Will return "image:x*"
    String wholeID = DocumentsContract.getDocumentId(contentUri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
            new String[] { id }, null);

    String filePath = "";

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }

    cursor.close();
    return filePath;
}


回答3:

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 the 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 two 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);
    }