【问题标题】:Null Pointer Exception when grabbing picture from Gallery从图库中抓取图片时出现空指针异常
【发布时间】:2014-02-12 03:40:34
【问题描述】:

我有以下代码,用于抓取图像(从相机或画廊),然后将其显示在 ImageView 上:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(resultCode == RESULT_OK)
    {
        if(requestCode == 1888)
        {
            final boolean isCamera;
            if(data == null)
            {
                isCamera = true;
            }
            else
            {
                final String action = data.getAction();
                if(action == null)
                {
                    isCamera = false;
                }
                else
                {
                    isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }

            Uri selectedImageUriTemp;
            Uri selectedImageUri;
            if(isCamera)
            {
                selectedImageUriTemp = outputFileUri;
                Bitmap image = decodeFile(new File(selectedImageUriTemp.getPath()));
                selectedImageUri = getImageUri(image);
            }
            else
            {
                selectedImageUriTemp = data == null ? null : data.getData();
                Bitmap image = decodeFile(new File(selectedImageUriTemp.getPath()));
                selectedImageUri = getImageUri(image);
            }

            Log.i("TAG", "IMAGEURI: " + selectedImageUri);

            pictureThumb.setImageURI(selectedImageUri);
            setRealPath(selectedImageUri);
        }
    }
}

private Uri getImageUri(Bitmap image){
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(getApplicationContext().getContentResolver(), image, "Title", null);
    return Uri.parse(path);
}

如果我尝试使用相机抓取图像,则代码有效,但是当我尝试从图库中抓取图像时,它会返回 NULL 指针异常。

谁能建议我正确的方向?谢谢

这是完整的日志:

02-12 10:34:56.249: E/AndroidRuntime(14607): FATAL EXCEPTION: main
02-12 10:34:56.249: E/AndroidRuntime(14607): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=Intent { dat=content://media/external/images/media/29 }} to activity {com.gelliesmedia.thumbqoo/com.gelliesmedia.thumbqoo.PictureBooth}: java.lang.NullPointerException: uriString
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3216)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3259)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.app.ActivityThread.access$1100(ActivityThread.java:138)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1253)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.os.Looper.loop(Looper.java:137)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.app.ActivityThread.main(ActivityThread.java:4954)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at java.lang.reflect.Method.invokeNative(Native Method)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at java.lang.reflect.Method.invoke(Method.java:511)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at dalvik.system.NativeStart.main(Native Method)
02-12 10:34:56.249: E/AndroidRuntime(14607): Caused by: java.lang.NullPointerException: uriString
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.net.Uri$StringUri.<init>(Uri.java:464)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.net.Uri$StringUri.<init>(Uri.java:454)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at android.net.Uri.parse(Uri.java:426)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at com.gelliesmedia.thumbqoo.PictureBooth.getImageUri(PictureBooth.java:224)
02-12 10:34:56.249: E/AndroidRuntime(14607):    at com.gelliesmedia.thumbqoo.PictureBooth.onActivityResult(PictureBooth.java:206)

【问题讨论】:

    标签: android android-camera android-camera-intent


    【解决方案1】:

    你的onActivityResult很乱。

    尝试以这种方式编写代码.. 下面的两个方法分别定义为从相机捕获图像和从图库中获取图像。

    protected void captureFromCamera() {
            // TODO Auto-generated method stub
            Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    
            startActivityForResult(cameraIntent,
                    UploadProfilePicActivity.REQ_CAMERA);
        }
    
        private void selectImageFromGallery() {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,
                    getString(R.string.upload_profile_photo)),
                    UploadProfilePicActivity.REQ_GALLERY);
        }
    

    现在 onActivityResult 你的代码可能是这样的......

    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == UploadProfilePicActivity.REQ_GALLERY && data != null
                    && data.getData() != null) {
                Uri _uri = data.getData();
                try {
                    Bitmap profileBmp = Media.getBitmap(getContentResolver(), _uri);
                    if (profileBmp != null) {
                        image.setImageBitmap(profileBmp);
                    }
    
                } catch (OutOfMemoryError e) {
                    Utility.displayToast(context,
                            getString(R.string.err_large_image));
                } catch (Exception e) {
    
                }
            } else if (requestCode == UploadProfilePicActivity.REQ_CAMERA
                    && data != null) {
                try {
                    Bitmap profileBmp = (Bitmap) data.getExtras().get("data");
                    if (profileBmp != null) {
                        image.setImageBitmap(profileBmp);
                    }
                } catch (OutOfMemoryError e) {
                    Utility.displayToast(context,
                            getString(R.string.err_large_image));
                } catch (Exception e) {
                }
            }
        }
    

    使用参数(即requestCoderesponseCode)更好地实现onActivityResult

    【讨论】:

      【解决方案2】:

      试试这个代码:

      在你的 xml 中创建一个图像视图

      ImageView photoFrame;
      public static final int REQ_CODE_PICK_IMAGE         = 101;
      

      在 oncreate 中添加:

        photoFrame.setOnClickListener(new OnClickListener() {
      
                  @Override
                  public void onClick(View arg0) {
                      try
                      {
                          Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                                     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                          startActivityForResult(galleryIntent, REQ_CODE_PICK_IMAGE); 
                      }catch(Exception e)
                      {
                          e.printStackTrace();
                      }
                  }
              });
      

      在 OnActivityResult 添加此代码:

             protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          switch(requestCode) { 
          case REQ_CODE_PICK_IMAGE:
              if(resultCode == RESULT_OK)
              {  
                  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]);
                  photoPath = cursor.getString(columnIndex);
                  cursor.close();
                  photoFrame.setImageBitmap(Utils.getScaledImage(photoPath, 120, 120));
              }
          }
      }
      

      为 Utils 创建一个类,在其中添加以下代码:

          public static Bitmap getScaledImage(String path, int width, int height){
              try {
                  //decode image size
                  BitmapFactory.Options o = new BitmapFactory.Options();
                  o.inJustDecodeBounds = true;
                  BitmapFactory.decodeFile(path ,o);              
                  //Find the correct scale value. It should be the power of 2.
                  final int REQUIRED_SIZE=70;
                  int width_tmp=o.outWidth, height_tmp=o.outHeight;
                  int scale=1;
                  while(true){
                      if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                          break;
                      width_tmp/=2;
                      height_tmp/=2;
                      scale++;
                  }
      
                  //decode with inSampleSize
                  BitmapFactory.Options o2 = new BitmapFactory.Options();
                  o2.inSampleSize=scale;
                  Bitmap scaledPhoto = BitmapFactory.decodeFile(path, o2);
                  scaledPhoto = Bitmap.createScaledBitmap(scaledPhoto, width, height, true);
                  return scaledPhoto;
              } 
              catch (Exception e) {
                  e.printStackTrace();
              }
              return null;
          }
      

      使用此代码,您可以从图库中选择图像,然后可以在 Imageview 上查看图像

      【讨论】:

        【解决方案3】:

        试试我的工作代码,图库图片需要使用它的 id 从 mediastore 查询

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
        
            if(resultCode == RESULT_OK)
            {
                if(requestCode == CAMERA_PIC_REQUEST)
                {               
                    loadCameraImage();
                    // Loading from camera is based on the intent passed
                }
                else if(requestCode == SELECT_PICTURE)
                {
                    Uri currentUri = data.getData();
                    String realPath = getRealPathFromURI(currentUri);   
            // You will get the real path here then you can work with that path as normal
                }
            }
        
        }
        
            // Gets the real path from MEDIA
        public String getRealPathFromURI(Uri contentUri) {
        
            String [] proj={MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query( contentUri, proj, null, null, null); 
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
        
            return cursor.getString(column_index);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多