Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android camera intent returns null... sometimes [duplicate]

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?

like image 741
moictab Avatar asked May 11 '14 12:05

moictab


1 Answers

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!

like image 116
GuilhE Avatar answered Nov 17 '22 01:11

GuilhE