Android - Camera activity gets opened instead of p

2019-08-30 12:34发布

问题:

I've created an activity that allows the user to add a picture to an ImageView in that activity. I've created a button, that opens a context menu for the activity and gives the user options to either pick a picture from the gallery or take a picture with camera.

If I choose the first option - to pick a picture from the gallery, it works without problems. Gallery is opened, I pick the picture, my activity is resumed and the picture is added to the ImageView.

Strange things start happening after choosing the second option, taking the picture and resuming to my activity:

  1. If I open the context menu again and try to open the gallery, camera activity gets opened instead
  2. I close the camera activity and resume to my activity, "Complete action using" dialog is shown
  3. I open the gallery, pick a picture and NullPointerException is thrown

Why am I having this behavior and an exception? I've tried searching for similar topics but haven't found a solution.
Below are the methods for my activity

public boolean onContextItemSelected(MenuItem item) {
    super.onContextItemSelected(item);
    switch(item.getItemId()) {
    case R.id.cm_Select_picture: {
        // TODO open gallery
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, ""), RC_SELECT_PICTURE);
    }
    case R.id.cm_Take_picture: {
        // TODO open camera 
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, RC_TAKE_PICTURE);
    }
    default: return false;
    }
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK) {
        switch(requestCode) {
        case RC_SELECT_PICTURE: {
            Log.d(TAG, "Case select picture");
            Uri selectedImageUri = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImageUri
                    , filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Bitmap pic = BitmapFactory.decodeFile(filePath);
            goodsImage.setImageBitmap(pic);
        }
        case RC_TAKE_PICTURE: {
            Log.d(TAG, "Case take picture");
            if(data.getExtras().get("data") != null) {
                Bitmap pic = (Bitmap) data.getExtras().get("data");
                goodsImage.setImageBitmap(pic);
            }
        }
        }
    }
}


04-26 01:34:59.529: E/AndroidRuntime(20531): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { dat=content://media/external/images/media/9 }} to activity {com.forestassistant/com.statistics.GoodsActivity}: java.lang.NullPointerException

回答1:

i used to call camera activity from my activity, and it worked well, here is my code:

 setMediaUri(getNewMediaFilePath(actOwner.getContentResolver()));
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getMediaUri());
                startActivityForResult(cameraIntent, CAMERA_CAPTURE_REQUEST_CODE);

and when result callback

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK 
            && requestCode == CAMERA_CAPTURE_REQUEST_CODE) {
        Drawable toRecycle= imgView.getDrawable();
        if (toRecycle != null) {                
            ((BitmapDrawable)imgView.getDrawable()).getBitmap().recycle();
        }
        mImg = decodeFileIntoRequiredSize(getPath(getMediaUri(),this), requiredSizeForImage);
        imgView.setImageBitmap(mImg);           
    } 
public Bitmap decodeFileIntoRequiredSize(String filePath,int requiredSize){
    Bitmap b = null;
    try {
        File f = new File(filePath);
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();
        int scale = 1;
        if (o.outHeight > requiredSize || o.outWidth > requiredSize) {
            scale = (int)Math.pow(2, (int) Math.round(Math.log(requiredSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
    } catch (IOException e) {
    }
    return b;
}
public String getPath(Uri uri,Activity act) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = act.managedQuery(uri, projection, null, null, null);
    if (cursor != null) {       
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}
public Uri getNewMediaFilePath(ContentResolver contentResolver) {
    ContentValues values = new ContentValues();

    //create the directory
    // /mnt/sdcard/DCIM/Camera/IMG_20111101_111922.jpg
    String cameraDir = "/Camera";
    //File dir1 = act.getExternalFilesDir(Environment.DIRECTORY_DCIM);
    File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+cameraDir);
    if(!dir.exists()) dir.mkdir();

    //use date as filename
    String name = "IMG_" + (String) android.text.format.DateFormat.format("yyyyMMdd_hhmmss",new Date());
    String path = dir.getPath()+File.separator + name;
    values.put(MediaStore.MediaColumns.TITLE, name);
    values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
    Uri base = null;
    path += ".jpg";
    base = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, path);
    return contentResolver.insert(base, values);
}

Hope this help you.