相机对象是一个空指针

Camera object is a null pointer

我从各种教程中获得了以下代码,但我无法执行,有人可以帮我纠正错误吗?我尝试调试应用程序以检查相机对象返回 null 但无法理解的原因,在此先感谢

Video.java

public class Video extends Activity {

    private Camera mCamera;
    private MediaRecorder mediaRecorder;
    private Context myContext;
    private LinearLayout cameraPreview;
    private Camera_Preview mPreview;
    Button s;
    boolean recording = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        myContext = this;
        initialize();
        capture();

    }

    private void initialize() {
        // TODO Auto-generated method stub

        cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);

        mPreview = new Camera_Preview(myContext, mCamera);

        cameraPreview.addView(mPreview);




    }

    private void capture() {
        // TODO Auto-generated method stub


        if (recording) {
            // stop recording and release camera
            mediaRecorder.stop(); // stop the recording
            releaseMediaRecorder(); // release the mediaRecoder object
            Toast.makeText(Video.this, "Video Captured", Toast.LENGTH_LONG).show();
            recording = false;
        } 
        else 
        {
            if (!prepareMediaRecorder())
            {
                Toast.makeText(Video.this, "Fail in prepareMediaRecorder()!",
                        Toast.LENGTH_LONG).show();
                finish();
            }
            // work on Ui thread for better performance
            runOnUiThread(new Runnable() {
                public void run() {
                    // If there are stories, add them to the table

                    try {
                        mediaRecorder.start();
                    } catch (final Exception ex) {
                        // Log.i("---","Exception in thread");

                    }
                }
            });
            recording = true;
        }

    }

    private boolean prepareMediaRecorder() {
        // TODO Auto-generated method stub

        mediaRecorder = new MediaRecorder();

        mCamera.open();
        mediaRecorder.setCamera(mCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile
                .get(CamcorderProfile.QUALITY_720P));

        mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
        mediaRecorder.setMaxDuration(200000); // Set max duration 20 sec.
        // mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    private void releaseMediaRecorder() {
        // TODO Auto-generated method stub

        if (mediaRecorder != null) {
            mediaRecorder.reset(); // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            mCamera.lock(); // lock camera for later use
        }
    }

}

Camera_Preview.java

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Camera_Preview extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder mHolder;
    private Camera mCamera;

    public Camera_Preview(Context context, Camera camera) {
        super(context);
        // TODO Auto-generated constructor stub

        mCamera = camera;
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub

        try {
            // create the surface and start camera preview
            if (mCamera == null) {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException e) {
            Log.d(VIEW_LOG_TAG, "Error setting camera preview: " + e.getMessage());
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub

        refreshCamera(mCamera);
    }

    private void refreshCamera(Camera camera) {
        // TODO Auto-generated method stub

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }
        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }
        // set preview size and make any resize, rotate or
        // reformatting changes here
        // start preview with new settings
        setCamera(camera);
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            Log.d(VIEW_LOG_TAG, "Error starting camera preview: " + e.getMessage());
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

    }

    public void setCamera(Camera camera) {
        //method to set a camera instance
        mCamera = camera;
    }

}

video.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical" >
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.69"
        android:background="#8cc172" >

        <Button
            android:id="@+id/button_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="33dp"
            android:text="STOP" />

    </RelativeLayout>

</LinearLayout>

LOGCAT:

04-13 12:18:42.368: E/AndroidRuntime(28442): FATAL EXCEPTION: main
04-13 12:18:42.368: E/AndroidRuntime(28442): Process: com.example.sp_2, PID: 28442
04-13 12:18:42.368: E/AndroidRuntime(28442): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sp_2/com.example.sp_2.Video}: java.lang.NullPointerException: camera object is a NULL pointer
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread.access0(ActivityThread.java:144)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.os.Looper.loop(Looper.java:136)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread.main(ActivityThread.java:5146)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at java.lang.reflect.Method.invokeNative(Native Method)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at java.lang.reflect.Method.invoke(Method.java:515)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at dalvik.system.NativeStart.main(Native Method)
04-13 12:18:42.368: E/AndroidRuntime(28442): Caused by: java.lang.NullPointerException: camera object is a NULL pointer
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.media.MediaRecorder.setCamera(Native Method)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at com.example.sp_2.Video.prepareMediaRecorder(Video.java:94)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at com.example.sp_2.Video.capture(Video.java:64)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at com.example.sp_2.Video.onCreate(Video.java:33)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.Activity.performCreate(Activity.java:5231)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-13 12:18:42.368: E/AndroidRuntime(28442):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
04-13 12:18:42.368: E/AndroidRuntime(28442):    ... 11 more

调试器:

mCamera=null

在清单文件中添加以下行

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

在您的 Video.java Initialize 方法中,您这样做:

mPreview = new Camera_Preview(myContext, mCamera);

但是,您实际上从未将任何东西分配给相机变量。看看这个文档,它应该告诉你你需要的一切: http://developer.android.com/training/camera/cameradirect.html#TaskOpenCamera

祝你好运