setPreviewDisplay(holder)中的NullPointerException

时间:2013-05-21 13:14:13

标签: java android-camera

这个Android的东西很新,并得到一个我似乎无法弄清楚的NullPointException。我试图在我的CameraActivity中实现一个onResume()方法,并将onCreate()中的几乎所有原始代码移动到onResume(),然后在onCreate()中调用onResume()。当代码在onCreate()中时,活动工作正常,但当置于onResume()时,异常会被激活。造成这种情况的原因是什么?

package com.example.tensioncamapp_project;

import java.io.IOException;

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

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "PreviewAactivity";
private SurfaceHolder mHolder;
private Camera mCamera;


public CameraPreview(Context context, Camera camera) {
    super(context);
    this.mCamera = camera;

    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
    this.mHolder = getHolder();
    this.mHolder.addCallback(this);
}

/**Displays the picture on the camera */
public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, now tell the camera where to draw the preview.
    try {
        this.mCamera.setPreviewDisplay(holder);
        this.mCamera.startPreview();
    } catch (IOException e) {
        Log.d(TAG, "Error setting camera preview: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
   this.mCamera.release();
    this.mCamera = null;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    //add things here
}
}

和我的CameraActivityClass

package com.example.tensioncamapp_project;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.content.Intent;
import android.app.Activity;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;

public class CameraActivity extends Activity {
private ImageButton captureButton;
private Camera mCamera;
    private CameraPreview mPreview;
    private PictureCallback mPicture;
    private ImageView imageView;
    private static final int STD_DELAY = 400;
    private static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = "CameraActivity";

/**Starts up the camera */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    onResume();

}   


/**Connects the capture button on the view to a listener
 *  and redirects the client to a preview of the captures image*/
private void addListenerOnButton() {
    this.captureButton = (ImageButton) findViewById(R.id.button_capture_symbol);
    this.captureButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View capturebutton) {
            mCamera.takePicture(null, null, mPicture);
            delay();
            Intent viewPic = new Intent(CameraActivity.this,      ViewPicActivity.class);
            startActivity(viewPic);
        }
    });
}


/** A safe way to get an instance of the Camera object. Code collected from elsewhere */
public static Camera getCameraInstance(){
    Camera c = null;
    try {
        // attempt to get a Camera instance
        c = Camera.open(); 
        //getting current parameters
        Camera.Parameters params = c.getParameters(); 
        //setting new parameters with flash
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        c.setParameters(params); 
    }
    catch (Exception e){
        // camera is not available (in use or does not exist)
    }
    // returns null if camera is unavailable
    return c; 
}

/**Generates a delay needed for application to save new pictures */
private void delay(){
    try {
        //Makes the program inactive for a specific amout of time
        Thread.sleep(STD_DELAY);
    } catch (Exception e) {
        e.getStackTrace();
    }
}

/**Method for releasing the camera immediately on pause event*/
@Override
protected void onPause() {
    super.onPause();
    //Shuts down the preview shown on the screen
    mCamera.stopPreview();
    //Calls an internal help method to restore the camera
    releaseCamera();             
}


/**Help method to release the camera */
private void releaseCamera(){
    //Checks if there is a camera object active
    if (this.mCamera != null){
        //Releases the camera
        this.mCamera.release();
        //Restore the camera object to its initial state
        this.mCamera = null;
    }
}

/**Activates the camera and makes it appear on the screen */
    protected void onResume() {
    // TODO Auto-generated method stub
    // deleting image from external storage
    FileHandler.deleteFromExternalStorage();
    // Create an instance of Camera.
    this.mCamera = getCameraInstance();
    // Create our Preview view and set it as the content of our activity.
    this.mPreview = new CameraPreview(this, this.mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(this.mPreview); 
    //add the capture button
    addListenerOnButton();
    // In order to receive data in JPEG format
    this.mPicture = new PictureCallback() {

        /**Creates a file when a image is taken, if the file doesn't already exists*/
        @Override 
        public void onPictureTaken(byte[] data, Camera mCamera) {

        File pictureFile = FileHandler.getOutputMediaFile(MEDIA_TYPE_IMAGE);

        if (pictureFile == null){
            Log.d(TAG, "Error creating media file, check storage permissions");
            return;
        }

        try {
            //Writes the image to the disc
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }
};
    super.onResume();
}



}

Log cat:

05-21 14:32:05.424: D/OpenGLRenderer(1030): Enabling debug mode 0
05-21 14:32:10.986: E/CameraActivity(1030): camera not availableFail to connect to   camera service
05-21 14:32:11.033: I/Choreographer(1030): Skipped 66 frames!  The application may be doing too much work on its main thread.
05-21 14:32:11.203: W/EGL_emulation(1030): eglSurfaceAttrib not implemented
05-21 14:32:13.013: D/AndroidRuntime(1030): Shutting down VM
05-21 14:32:13.013: W/dalvikvm(1030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-21 14:32:13.083: E/AndroidRuntime(1030): FATAL EXCEPTION: main
05-21 14:32:13.083: E/AndroidRuntime(1030): java.lang.NullPointerException
05-21 14:32:13.083: E/AndroidRuntime(1030):     at com.example.tensioncamapp_project.CameraPreview.surfaceCreated(CameraPreview.java:33)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.SurfaceView.access$000(SurfaceView.java:86)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.Choreographer.doFrame(Choreographer.java:532)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.os.Handler.handleCallback(Handler.java:725)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at android.os.Looper.loop(Looper.java:137)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at    android.app.ActivityThread.main(ActivityThread.java:5041)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at    java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at java.lang.reflect.Method.invoke(Method.java:511)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-21 14:32:13.083: E/AndroidRuntime(1030):     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:2)

解决方法是在if语句中调用onResume()中的getCameraInstancemethod()

protected void onResume() {
    // TODO Auto-generated method stub
    // deleting image from external storage
    FileHandler.deleteFromExternalStorage();
    // Create an instance of Camera.
    if (this.mCamera == null){
        this.mCamera = getCameraInstance();}

答案 1 :(得分:1)

我认为你的问题在这里

this.mPreview = new CameraPreview(this, this.mCamera);

this.mCamera似乎是null,它不是设置类的新实例,这需要在getCameraInstance()方法中完成。

答案 2 :(得分:0)

如果抛出异常,

getCameraInstance()将返回null。 这导致NPE this.mCameranull

您应该检查getCameraInstance中是否抛出异常并正确处理。最基本的是记录它并尝试理解原因。