Search code examples
androidandroid-camera-intent

Get uri of picture taken by camera


When the user takes a picture with the camera, I want the image displayed in an ImageView and I want to save the Uri to an online database. I heard saving the Uri of a picture is better than saving the path.

So this is how I start the camera:

intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getFile(getActivity()))); 
String a = String.valueOf(Uri.fromFile(getFile(getActivity())));
intent.putExtra("photo_uri", a);
startActivityForResult(intent, PICK_FROM_CAMERA);

where

private File getFile(Context context){
  File sdCard = Environment.getExternalStorageDirectory();
  File directory = new File (sdCard.getAbsolutePath() + "/Myapp");
  if (!directory.exists()) {
       directory.mkdirs();
  }
  String filename = "bl" + System.currentTimeMillis() + ".jpg";
  File newFile = new File(directory, filename);

  return newFile;
}

In onActivityResult:

Bundle extras = data.getExtras();
String photo_uri = extras.getString("photo_uri"); //null

This is always null. Btw before sending the intent the Uri looks like file://... instead of content:// which is the uri when I open an image from the gallery. I don't know if that's a problem.

Also, should I save the path instead of the Uri to the database? I read that the Uri can be complicated in certain phones or Android versions. When I let the user select an image from the gallery, I save the Uri to the database, so I think the best way is saving the Uri in this case as well.

I tried out many variations, but I get null every time I try to pass a variable with the intent...


Solution

  • After starting the intent:

    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    
    startActivityForResult(intentPicture,PICK_FROM_CAMERA); 
    

    In onActivityResult:

    case PICK_FROM_CAMERA:
    
       Uri selectedImageUri = data.getData();
       InputStream imageStream = null;
       try {
           imageStream = getContentResolver().openInputStream(selectedImageUri);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);   
    break;
    

    That's all.