无法从摄像头捕获图像获取NullPointerException

时间:2015-06-15 10:38:28

标签: android

使用相机类,我正在编写简单的代码来捕捉图像 按钮,但我得到NullPointerException

下面是代码。

SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
Camera mCamera;
ImageView mButton;

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mSurfaceView = (SurfaceView) this.findViewById(R.id.CameraView);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mSurfaceHolder.addCallback(this);

    mSurfaceView.setFocusable(true);
    mSurfaceView.setFocusableInTouchMode(true);
    mSurfaceView.setClickable(true);

    mButton = (ImageView)findViewById(R.id.capture);
    mButton.setOnClickListener(this);
}

@SuppressWarnings("deprecation")
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    mCamera.startPreview();
}

@SuppressWarnings("deprecation")
@Override
public void surfaceCreated(SurfaceHolder holder) {
    mCamera = Camera.open();
    try {
        mCamera.setPreviewDisplay(holder);
        Camera.Parameters mParameters = mCamera.getParameters();
        if (this.getResources().getConfiguration().orientation !=
                Configuration.ORIENTATION_LANDSCAPE) {
            mParameters.set("orientation", "portrait");
            mCamera.setDisplayOrientation(90);
        } else {
            mParameters.set("orientation", "landscape");
            mCamera.setDisplayOrientation(0);
        }
        mCamera.setParameters(mParameters);
        mCamera.setPreviewDisplay(holder);
    } catch (IOException e) {
        mCamera.release();
    }
    mCamera.startPreview();
}

@SuppressWarnings("deprecation")
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    mCamera.stopPreview();
    mCamera.release();
}

@SuppressWarnings("deprecation")
@Override
public void onPictureTaken(byte[] data, Camera camera) {
    try {
        Uri imageFileUri = this.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

        OutputStream imageFileOS = getContentResolver().openOutputStream(imageFileUri);
        imageFileOS.write(data);
        imageFileOS.flush();
        imageFileOS.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); 
    }
    mCamera.startPreview();
}

@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
    mCamera.takePicture(null, null, SnapShot.this);
}

我在这里得到NullPointerExeption:

this.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

AndroidManifest.xml如下所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".SnapShot"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

下面是logcat显示错误消息

E/DatabaseUtils(  718): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference

E/DatabaseUtils(  718):     at com.android.providers.media.MediaProvider.insertFile(MediaProvider.java:3151)

E/DatabaseUtils(  718):     at com.android.providers.media.MediaProvider.insertInternal(MediaProvider.java:3543)

E/DatabaseUtils(  718):     at com.android.providers.media.MediaProvider.insert(MediaProvider.java:2959)

E/DatabaseUtils(  718):     at android.content.ContentProvider$Transport.insert(ContentProvider.java:235)

E/DatabaseUtils(  718):     at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)

E/DatabaseUtils(  718):     at android.os.Binder.execTransact(Binder.java:446)

W/System.err(11632): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference

W/System.err(11632):    at android.os.Parcel.readException(Parcel.java:1546)

W/System.err(11632):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)

W/System.err(11632):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)

W/System.err(11632):    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:475)

W/System.err(11632):    at android.content.ContentResolver.insert(ContentResolver.java:1207)

W/System.err(11632):    at com.parashu.mycamera.SnapShot.onPictureTaken(SnapShot.java:87)

W/System.err(11632):    at android.hardware.Camera$EventHandler.handleMessage(Camera.java:1094)

W/System.err(11632):    at android.os.Handler.dispatchMessage(Handler.java:102)

W/System.err(11632):    at android.os.Looper.loop(Looper.java:135)

W/System.err(11632):    at android.app.ActivityThread.main(ActivityThread.java:5221)

W/System.err(11632):    at java.lang.reflect.Method.invoke(Native Method)

W/System.err(11632):    at java.lang.reflect.Method.invoke(Method.java:372)

W/System.err(11632):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)

W/System.err(11632):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

D/GDP     (11632): NullPointerException

E/QCameraHWI(  189): android::status_t android::QCameraHardwareInterface::setPreviewWindow(preview_stream_ops_t*): bug, cannot handle new window in started state

E/mm-camera(  201): config_v2_proc_event_message_0: Unsupported message id: 40

E/mm-camera(  201): config_MSG_ID_STOP_ACK: streamon_mask is not clear. Should not call PP_Release_HW

D/QCameraHWI(  189): android::status_t android::QCameraHardwareInterface::startPreview():  start preview now

I/QCameraHWI(  189): android::status_t android::QCameraHardwareInterface::startPreview2():Setting ZSL mode

E/mm-camera(  201): config_proc_CAMERA_SET_INFORM_STARTPREVIEW

E/mm-camera(  201): config_update_stream_info Storing stream parameters for video inst 1 as : width = 640, height 480, format = 1 inst_handle = 810081 cid = 0

E/mm-camera(  201): config_update_stream_info Storing stream parameters for video inst 3 as : width = 640, height 480, format = 1 inst_handle = 830083 cid = 0

E/mm-camera(  201): config_update_stream_info Storing stream parameters for video inst 4 as : width = 512, height 384, format = 1 inst_handle = 840084 cid = 0

E/mm-camera(  201): config_decide_vfe_outputs: Ports Used 3, Op mode 1

E/mm-camera(  201): config_decide_vfe_outputs Current mode 5 Full size streaming : Disabled

E/mm-camera(  201): config_decide_vfe_outputs: Primary: 640x480, extra_pad: 0x0, Fmt: 1, Type: 1, Path: 1

E/mm-camera(  201): config_decide_vfe_outputs: Secondary: 640x480, extra_pad: 0x0, Fmt: 1, Type: 3, Path: 4

E/mm-camera(  201): config_update_inst_handles Updated the inst handles as 810081, 830083, 0, 0 

E/mm-camera(  201): camif_client_set_params: camif has associated with obj mask 0x1

E/mm-camera(  201): config_v2_CAMERA_START_common CAMIF_PARAMS_ADD_OBJ_ID failed -1 

E/mm-camera(  201): vfe_operation_config: format 3

E/mm-camera(  201): vfe_operation_config:vfe_op_mode=5

E/mm-libcamera2(  189): PROFILE HAL: First preview frame received: 1434375940.660242458

E/QCameraHWI_Preview(  189): processPreviewFrameWithDisplay: buffer to be enqueued is not locked

D/audio_hw_primary(  189): disable_audio_route: reset and update mixer path: low-latency-playback

D/audio_hw_primary(  189): disable_snd_device: snd_device(2: speaker)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题解决了。 Media.EXTERNAL_CONTENT_URI默认导入android.provider.MediaStore.Audio.Media; So I used below code, it worked fine. getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXT‌​E‌​RNAL_CONTENT_URI, new ContentValues());