Android - 相机活动被打开而不是图片库

时间:2012-04-25 23:20:00

标签: android nullpointerexception android-camera android-gallery

我创建了一个活动,允许用户将图片添加到该活动中的ImageView。我创建了一个按钮,可以打开活动的上下文菜单,可以让用户选择从图库中选择图片或者用相机拍照

如果我选择第一个选项 - 从图库中选择图片,它可以正常工作。画廊打开,我选择图片,我的活动恢复,图片被添加到ImageView。

选择第二个选项,拍摄照片并恢复到我的活动后,会发生奇怪的事情:

  1. 如果我再次打开上下文菜单并尝试打开相册 活动被打开了
  2. 我关闭相机活动并恢复到我的活动,显示“使用完成操作”对话框
  3. 我打开画廊,选择一张照片并抛出NullPointerException
  4. 为什么我会出现此行为并出现异常?我尝试过搜索类似主题但未找到解决方案。
    以下是我的活动方法

    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 个答案:

答案 0 :(得分:1)

我以前从我的活动中调用了相机活动,而且效果很好,这是我的代码:

 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);

以及结果回调

@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);
}

希望这对你有所帮助。