Android Camera Real Tutorial

In mobile development, we have two extreme giants: Apple and Google. Apple tends to be glorify the sample code just like BMW, and Google organize the documentation with problematic source codes. In this weekend, I struggle with sample codes and tutorials from Google (Camera Example). BTW, in case if you are working with programmers as a product manager, this is a useful tip. When a programmer says, “I struggle for an half hour” means, he might already pulled his hair for 3-4 hours, and it’s my case today.

This is basic steps when you call the Camera Intent.

  1. Prepare for the directory to save the image
  2. Create Intent with Camera option
  3. Start Activity with the intent. When you start it, don’t forget to speicify the request code.

	public static final int CAMERA_REQUEST = 1000;
	public Uri mFileUri = null;

	public void onCreate(Bundle savedInstanceState) {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraTest");
		mediaStorageDir.mkdir(); // make sure you got this folder
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
		mFileUri = Uri.fromFile(mediaFile)                   ;
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);// this line causes issue - onActivityResult not called...
		startActivityForResult(intent, CAMERA_REQUEST);

After calling the intent, the result will be back in onActivityResult method. Let’s assume the user took a picture, and clicked OK icon. In the Google example above, it did not cover the case that onActivityResult gives null for the Intent in the argument. The workaround is to keep the file path in the member variable, and get the Image using Uri.fromFile method. Check the source code below.

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_REQUEST) {
			if (resultCode == RESULT_OK) {
				// Oopse ! data is null somehow. wtf
				//Toast.makeText(this, "Saved: " + data.getData(), 10).show();

				try {
					Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),mFileUri);
					Toast.makeText(this,"Saved : " + bitmap.getByteCount() + " bytes" , 10).show();
				catch (IOException e) {
			else if (resultCode == RESULT_CANCELED) {
				Log.v("mylog","camera canceled");
			else {
				Log.v("mylog","camera error");
		}// eo if requestCode
	}// eo onActivityResult

That’s it. I googled around all over the places, but this is the answer for it. I’m not sure the exact conditions which above codes applies. I’m using Galaxy S with Android 4.1.1.

By: kiichi on: