19

我按照Android 开发网站上相机上的说明进行操作

我只是启动相机意图,而不是构建自己的相机。

拍照后返回结果的处理示例代码如下。

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Image captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Image saved to:\n" +
                    data.getData(), Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }

    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:\n" +
                    data.getData(), Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the video capture
        } else {
            // Video capture failed, advise user
        }
    }
}

resultCode可以,但data始终为 NULL,这会导致 NPE。我查看了sdcard,照片真的保存在那里。任何提示?非常感谢。

更新:根据要求提供 logcat 信息:

   01-28 19:39:00.547: ERROR/AndroidRuntime(24315): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to resume activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.NullPointerException
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2455)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2483)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1997)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3362)
    at android.app.ActivityThread.access$700(ActivityThread.java:127)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1162)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4511)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.NullPointerException
    at android.app.ActivityThread.deliverResults(ActivityThread.java:2991)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2442)
    ... 13 more
    Caused by: java.lang.NullPointerException
    at com.example.CameraTest.MyCamera.onActivityResult(MyCamera.java:71)
    at android.app.Activity.dispatchActivityResult(Activity.java:4654)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:2987)
    ... 14 more                                                                                      
4

7 回答 7

26

您的代码的问题是:

data.getData()

此调用不会从返回Intent. data它从返回的字段中获取Intent可能是null.

您需要从返回的内容中获取额外的信息,Intent如下所示:

data.getExtras().get("data");

其他一些答案已经表明了这一点,嵌入在大量其他代码中。这使得很难真正看到问题所在。

于 2013-10-18T16:08:02.777 回答
8

这是一个类似问题的答案。好像是三星手机的问题。。。

基本上,如果您有这样的代码来创建 Intent:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

然后,在 中onActivityResult替换data.getData()fileUri.toString(),它将解决您的问题。

于 2014-05-22T09:14:19.643 回答
3

使用@KJ50 的解决方案,并使用savedInstanceState以确保您不会得到空值。

/**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }
于 2015-07-21T09:06:56.107 回答
2

试试下面的代码:

 Button m_btnCamera;
  ImageView m_ivCaptureImage;
  String m_curentDateandTime;
  String m_imagePath;
  Bitmap m_bitmap;

   //Start camera to caputre image.
 Intent m_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  m_intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
  startActivityForResult(m_intent, TAKE_PHOTO_CODE);

 private Uri getImageUri() throws CustomException
    {
    Uri m_imgUri = null;
    File m_file;
    try
    {
        SimpleDateFormat m_sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        m_curentDateandTime = m_sdf.format(new Date());
        m_imagePath = File.getPath() + File.separator + m_curentDateandTime + ".jpg";
        m_file = new File(m_imagePath);
        m_imgUri = Uri.fromFile(m_file);
    }
    catch (Exception p_e)
    {}      
    return m_imgUri;        
}

 @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data)
  {
  super.onActivityResult(requestCode, resultCode, data);
 if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK)
    {
        m_bitmap = ImageHelper.scaleImage(m_imagePath, 200, 200);
            m_bitmap = ImageHelper.rotateImage(m_bitmap, true, m_rotate);
            m_ivCaptureImage.setImageBitmap(m_bitmap);
    }
  }
}
于 2013-01-28T08:59:49.267 回答
0

试试这个

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {
        case PICK_IMAGE_ID:

            Bitmap bitmap = ImagePicker.getImageFromResult(this.getActivity(), resultCode, data);

            if(data!=null){
                //set image view
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}
于 2016-11-28T17:14:25.110 回答
0

此代码将帮助您

getData() 方法仅在 Android 版本高于 M 时返回数据,否则返回 null 结果。

if (resultCode == Activity.RESULT_OK) {

                //Check Android version, as intent.getData() will return data only if v is above or equal to M otherwise the data will be null
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
                    Uri selectedImageURI = imageReturnedIntent.getData();
                    Toast.makeText(getActivity(), "URI Path:" + selectedImageURI, Toast.LENGTH_LONG).show();
                } else {
                    Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                    String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), photo, "Title", null);
                    Uri selectedImageURI = Uri.parse(path);
                    Toast.makeText(getActivity(), "URI Path:" + selectedImageURI, Toast.LENGTH_LONG).show();
                }
            }
于 2018-08-06T06:10:29.523 回答
-1

试试下面的代码.....

btn_capture.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent cameraIntent = new  Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
        }
    });
 protected void onActivityResult(int requestCode, int resultCode, Intent data){


             if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
                 Bitmap photo = (Bitmap) data.getExtras().get("data"); 
                 img.setImageBitmap(photo);
             } 
          }

    }

最后,您将以下代码添加到清单中

   <uses-feature android:name="android.hardware.camera"></uses-feature> 
于 2013-01-28T09:30:09.753 回答