Android camera intent returns null… sometimes [dup

2019-02-17 08:27发布

问题:

This question already has an answer here:

  • Getting Uri Null in capture photo from camera intent in samsung mobile 3 answers

I am debugging my app in 2 different physical devices:

  • Motorola Moto G, Android 4.4.2
  • LG OPTIMUS L5 II, Android 4.1.2

I am calling the camera in a button:

buttonCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            }
        });

And I manage the intent result like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData(); // <-- Sometimes null
    }

The problem here is that data.getData() is null in the Motorola Moto G but not in the LG OPTIMUS, why is this? How can I avoid to get null in the Motorola Moto G?

回答1:

A bit late this answer but I had this same problem just now and I found a solution:

private static final String STATE_FILE_URI = "state_file_uri";
private static final int BROWSE_CAMERA = 111;
private String fileUri;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(STATE_FILE_URI, fileUri);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        fileUri = savedInstanceState.getString(STATE_FILE_URI);
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void takePictureIntent(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = "your_uri";
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileUri)));
        startActivityForResult(takePictureIntent, BROWSE_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {          
            if (requestCode == BROWSE_CAMERA) {
                if (data == null) {
                    onDeliveryPicture(Uri.parse("file://" + fileUri));
                } else {
                    onDeliveryPicture(data.getData());
                }
            }
        }
    }

    private void onDeliveryPicture(Uri uri) {
        ...
    }

Hope it helps!