4

I'm trying to capture image and save it in gallery. For that in onCreate my code

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
    imageUri = Uri.fromFile(photo);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, TAKE_PICTURE);

and

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {
        Log.v("data", "data: " + data);
        Bundle extras = data.getExtras();
        if (extras.containsKey("data")) {
            bitmap = (Bitmap) extras.get("data");
            // ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            // byte[] image = baos.toByteArray();
            if (bitmap != null) {
                // BitmapFactory.Options options = new
                // BitmapFactory.Options();
                // options.inSampleSize = 5;
                // Bitmap myImage = BitmapFactory.decodeByteArray(image, 0,
                // image.length, options);
                imageView.setImageBitmap(bitmap);
            }
        } else {
            Toast.makeText(getBaseContext(), "Please capture again", Toast.LENGTH_LONG).show();
        }
        showPopUpForUpload();
    }
}

Now I'm able to capture image, but after that I'm getting error

12-17 15:28:56.090: E/AndroidRuntime(4684): FATAL EXCEPTION: main
12-17 15:28:56.090: E/AndroidRuntime(4684): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example.fashiongirl/com.example.fashiongirl.HomeActivity}: java.lang.NullPointerException
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2744)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:2787)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread.access$2000(ActivityThread.java:122)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1032)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.os.Looper.loop(Looper.java:132)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread.main(ActivityThread.java:4025)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at java.lang.reflect.Method.invokeNative(Native Method)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at java.lang.reflect.Method.invoke(Method.java:491)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at dalvik.system.NativeStart.main(Native Method)
12-17 15:28:56.090: E/AndroidRuntime(4684): Caused by: java.lang.NullPointerException
12-17 15:28:56.090: E/AndroidRuntime(4684):     at com.example.fashiongirl.HomeActivity.onActivityResult(HomeActivity.java:47)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.Activity.dispatchActivityResult(Activity.java:4541)
12-17 15:28:56.090: E/AndroidRuntime(4684):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2740)
12-17 15:28:56.090: E/AndroidRuntime(4684):     ... 11 more

The null pointer exception is on line

Bundle extras = data.getExtras();

So what is the problem?

Shirish Herwade
  • 11,461
  • 20
  • 72
  • 111
  • why you are not using `imageView.setImageURI(imageUri);` instead of `imageView.setImageBitmap(bitmap); ` if requestCode is TAKE_PICTURE – ρяσѕρєя K Dec 17 '12 at 10:18
  • 1
    this is not only suggestion this is answer of your question because we get data back in case of if we are not passing image path with intent or in case of video . so try it in right way you will sure get image in imageview – ρяσѕρєя K Dec 17 '12 at 10:26
  • yes, you are right, that solves the problem, but sometimes I also want to send/upload this image to webservice, so is it possible using Uri. Can you tell me please how can I get the image using uri to upload it – Shirish Herwade Dec 17 '12 at 10:41
  • 1
    here ` File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg"); ` you are creating file on sdcard then use photo.getpath() for getting image path from sdcard for send/upload instead of uri – ρяσѕρєя K Dec 17 '12 at 10:47
  • 1
    @ρяσѕρєя K - Its only not work in Android 4.0 +. The same thing works in 2.2 , 2.3 .. – user370305 Dec 17 '12 at 10:51
  • thanks pra... and user370305. Now I have 2 options, get image from 1) intent using getExtras() or 2) using Uri, i.e. intent.putExtra(). So which 1 is more efficient than other or is recommended? – Shirish Herwade Dec 17 '12 at 10:56
  • 1
    I suggest you to check for both condition if your bundle is null then use uri and if your bundle is not null then use Bundle. I seen in some device Camera application store images in `DCIM` directory only not on the path given in `Extra` parameters of `Intent`. – user370305 Dec 17 '12 at 11:13

5 Answers5

6

I think its a problem of Android version 4.0 +.

Just try to remove,

File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

When you call Capture intent. Now your resulted bundle onActivityResult() is not NULL.

Actually, When you are giving MediaStore.EXTRA_OUTPUT parameter to Camera Intent then camera application doesn't callback with bundled data. (I find this issues in Android 4.0 +)

You have to get the Image file from Uri which you set as MediaStore.EXTRA_OUTPUT parameter.

Update:

Or use below pathFromUri() method and pass Uri which you are set to camera intent and get the Real File Path, now for this you don't have to use Bundle extras = data.getExtras();

private String pathFromUri(Uri imageUri) {
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(imageUri, filePathColumn,
                null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    return filePath ;
}
user370305
  • 108,599
  • 23
  • 164
  • 151
0

Its Working for me:-----try in this way

   @Override
  protected void onActivityResult(int requestCode, int resultCode,
        final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {

                try {
                            Uri selectedImage = intent.getData();
                            bmpSelectedImage = getThumbnail(selectedImage);
                            set_img_camera.setImageBitmap(bmpSelectedImage);

                        } catch (IOException e) {

                            e.printStackTrace();
                        }


        }

    }
Deepanker Chaudhary
  • 1,694
  • 3
  • 15
  • 35
0

This is my solution:

            Bitmap photo=null;
            File file = getTempFile(this);
            try {
                 photo = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );

                } catch (FileNotFoundException e) {
                  e.printStackTrace();
                } catch (IOException e) {
                  e.printStackTrace();
                }

            if (photo == null) // for newest android version +-4.0
            {
                Uri selectedImage = data.getData();
                photo = Media.getBitmap(this.getContentResolver(),
                        selectedImage);
            }

and

private File getTempFile(Context context) 
    final File path = new File(Environment.getExternalStorageDirectory(),
            context.getPackageName());
    if (!path.exists()) {
        path.mkdir();
    }
    return new File(path, "image.tmp");
}
xOslyx
  • 1
  • 1
0

Just check whether 'data' is null or not. If it is null, you should skip the code or it will make your app crash

if(data != null){    
        Bundle extras = data.getExtras();
                if (extras.containsKey("data")) {
                    bitmap = (Bitmap) extras.get("data");
                    // ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    // byte[] image = baos.toByteArray();
                    if (bitmap != null) {
                        // BitmapFactory.Options options = new
                        // BitmapFactory.Options();
                        // options.inSampleSize = 5;
                        // Bitmap myImage = BitmapFactory.decodeByteArray(image, 0,
                        // image.length, options);
                        imageView.setImageBitmap(bitmap);
                    }
                } else {
                    Toast.makeText(getBaseContext(), "Please capture again", Toast.LENGTH_LONG).show();
                }
                showPopUpForUpload();
    }
Teo Mihaila
  • 134
  • 1
  • 2
  • 18
0

Function to select / capture photo

public void selectPhoto(){
    final CharSequence[] options1 = { "Take Photo", "Choose from Gallery","Cancel" };
    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(activity);;
    builder.setTitle("Photo Upload");
    builder.setItems(options1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int item) {
            if (options1[item].equals("Take Photo")) {
                dispatchTakePictureIntent();
            } else if (options1[item].equals("Choose from Gallery")) {
                Intent pickPhoto = new Intent(Intent.ACTION_GET_CONTENT);
                pickPhoto.setType("image/*");
                activity.startActivityForResult(pickPhoto , 2);
            } else if (options1[item].equals("Cancel")) {
                dialogInterface.dismiss();
            }
        }
    });
    builder.show();
}

declare this variable inside the class

int RC;

after that you need to add the on result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    RC = requestCode;
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        if(data == null){return;}
        try {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            String path = MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "Title", null);
            Uri imageUri = Uri.parse(path);
            imageView.setImageURI(imageUri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }else if(requestCode == 2){
        if(data == null){return;}
        Uri imageUri = data.getData();
        imageView.setImageURI(imageUri);
    }
}