2016-07-23 88 views
1

我想要一個使用libgdx android的相機設備,我正在使用this code。 但是我在這條線上寫着NullPointerExceptionCamera.Parameters p = camera.getParameters();CameraSurface.java類。Libgdx android:camera.getParameters()崩潰應用程序空指針異常

package com.mygdx.cameradevice; 

import java.io.IOException; 
import android.content.Context; 
import android.hardware.Camera; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class CameraSurface extends SurfaceView implements SurfaceHolder.Callback { 

private Camera camera; 

public CameraSurface(Context context) { 
    super(context); 

    // We're implementing the Callback interface and want to get notified 
    // about certain surface events. 
    getHolder().addCallback(this); 
    // We're changing the surface to a PUSH surface, meaning we're receiving 
    // all buffer data from another component - the camera, in this case. 
    getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

} 

public void surfaceCreated(SurfaceHolder holder) { 
    // Once the surface is created, simply open a handle to the camera hardware. 
    camera = Camera.open(); 

} 
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    // This method is called when the surface changes, e.g. when it's size is set. 
    // We use the opportunity to initialize the camera preview display dimensions. 
    //System.out.println("ajay"); 
    //camera=Camera.open(); 
    Camera.Parameters p = camera.getParameters(); 
    p.setPreviewSize(width,height); 
    camera.setParameters(p); 

    // We also assign the preview display to this surface... 
    try { 
     camera.setPreviewDisplay(holder); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void surfaceDestroyed(SurfaceHolder holder) { 
    // Once the surface gets destroyed, we stop the preview mode and release 
    // the whole camera since we no longer need it. 
    camera.stopPreview(); 
    camera.release(); 
    camera = null; 
} 

public Camera getCamera() { 
    return camera; 
} 

} 
+0

所以,我猜''surfaceChanged'方法在'surfaceCreated'之前調用。無論如何看看[這裏](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Enigo

+0

你添加了相機的權限和閃光/硬件清單中的功能? – VVB

+0

是的,我在AndroidManifest.xml文件中添加了相機權限,並且在運行surfaceChanged後第一次運行surfaceCreated方法。因此,我在此線路上創建了NullPointerException。Camera.Parameters p = CameraSurface類中的camera.getParameters()。 –

回答

1

我看到你的代碼是從https://github.com/libgdx/libgdx/wiki/Integrating-libgdx-and-the-device-camera拷入, 我用的是相同的一個,然後我創建它的幫助下一個項目,在CameraSurface.java的代碼是一樣的,所以也許有某事別的錯了。 你可以看到我的簡單項目https://github.com/54wall/LibgdxAndroidCamera, 看到你和我的區別。我想在AndroidDeviceCameraController.class中的一些關鍵代碼。 我希望能幫到你!