0

我创建了一个活动,允许用户在该活动中向 ImageView 添加图片。我创建了一个按钮,用于打开活动的上下文菜单,并为用户提供从图库中选择图片或使用相机拍照的选项

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

后,奇怪的事情开始发生:

  1. 如果我再次打开上下文菜单并尝试打开图库,则会打开相机活动
  2. 我关闭相机活动并恢复我的活动,显示“使用完成操作”对话框
  3. 我打开图库,选择一张图片并抛出 NullPointerException

为什么我有这种行为和异常?我尝试搜索类似的主题,但没有找到解决方案。
以下是我的活动的方法

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
4

1 回答 1

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

希望这对您有所帮助。

于 2012-04-26T02:22:40.873 回答