2013-05-21 30 views
4

這個android東西很漂亮,並且得到一個NullPointException,我似乎無法弄清楚。我試圖在我的CameraActivity中實現一個onResume()方法,並將onCreate()中的所有原始代碼移至onResume(),然後在onCreate()中調用onResume()。當代碼在onCreate()中時,該活動正常工作,但在onResume()中放置異常arsises。是什麼造成的?setPreviewDisplay(持有者)中的NullPointerException

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(); 
} 



} 

登錄貓:

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) 
+0

很難看到這裏的行號,你可以提供的拋繩(CameraPreview.java:33)這個例外? – Rob

+0

/**在相機上顯示圖片*/ public void surfaceCreated(SurfaceHolder holder){//已經創建Surface,現在告訴相機在哪裏繪製預覽。 嘗試{this.mCamera.setPreviewDisplay(holder); ** //行導致異常 this.mCamera.startPreview(); (標記錯誤,設置攝像頭預覽:「+ e.getMessage());}}; catch(IOException e){ } catch(IOException e){ Log.d } } – Mat

+0

athospy

回答

0

getCameraInstance(),則返回null拋出異常。 這導致NPE爲this.mCameranull

您應該檢查getCameraInstance是否引發異常並正確處理。最基本的事情是記錄它並試圖理解原因。

+0

你是對的,getCameraInstance()拋出一個異常說」無法連接到相機服務「。我懷疑我沒有正確地釋放相機,但我無法弄清楚爲什麼......我在onPause()方法中釋放了相機。 – Mat

+0

您可以將異常的準確logcat添加到問題中。它可能會幫助你... – BobTheBuilder

+0

發佈整個日誌上面 – Mat

1

我覺得你的問題是在這裏

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

this.mCamera似乎是空,它不設置類的新實例,這需要在getCameraInstance()方法來完成。

2

解決的辦法是調用的onResume的getCameraInstancemethod()()的if語句

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();}