Android intent.getData()Nullpointer exceptipon

时间:2013-03-28 12:16:41

标签: java android

我有一个启动智能手机相机的Android应用程序

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST );

要显示拍摄的照片,我使用这段代码,

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    setImage=true;
    if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
        if(data!=null)
        {
            ImageView image = (ImageView) findViewById(R.id.imagePreview);
            Bundle extras = data.getExtras();
             Bitmap mImageBitmap = (Bitmap) extras.get("data");
             image.setImageBitmap(mImageBitmap);
        }
   }
}

这很好用,但如果我想获取拍摄照片的路径,我必须使用(intent)data.getData(),但这会返回null值。我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

试试如下:

      Bitmap m_photo = (Bitmap) p_data.getExtras().get("data");
    if (m_photo != null)
    {
    ByteArrayOutputStream m_upByteArrayOutputStream = new ByteArrayOutputStream();
    m_photo.compress(Bitmap.CompressFormat.PNG, 40, m_upByteArrayOutputStream);
    Drawable m_imageFromCamera = new BitmapDrawable(m_photo);
             image.setBackgroundDrawable(m_photo);
      }

<强>编辑:

要获取图像的路径,请尝试以下代码:

     Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String imagePath = cursor.getString(columnIndex); <---- Here is your image path.
        cursor.close();

答案 1 :(得分:0)

试试这个希望它会帮助你。

Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            String imageName = picturePath.substring(picturePath.lastIndexOf(
                    "/", picturePath.length()));