Getting NullPointerException in my custom Android

2019-07-31 16:24发布

I'm trying to build my first custom camera-app in Android.

On the emulator I get:

"Unfortunately, [app name] has stopped"

This is the error log: (if you want me to paste the full log, please say so)

11-13 19:14:04.023: E/AndroidRuntime(4474): FATAL EXCEPTION: main
11-13 19:14:04.023: E/AndroidRuntime(4474): java.lang.NullPointerException
11-13 19:14:04.023: E/AndroidRuntime(4474):     at com.kachingcamapp.CameraApplication.surfaceChanged(CameraApplication.java:80)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.SurfaceView.updateWindow(SurfaceView.java:554)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.SurfaceView.access$000(SurfaceView.java:81)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:671)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1818)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.Choreographer.doCallbacks(Choreographer.java:555)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.Choreographer.doFrame(Choreographer.java:525)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.os.Handler.handleCallback(Handler.java:615)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.os.Looper.loop(Looper.java:137)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at java.lang.reflect.Method.invoke(Method.java:511)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 19:14:04.023: E/AndroidRuntime(4474):     at dalvik.system.NativeStart.main(Native Method)

Here's my code:

public class CameraApplication extends Activity implements OnClickListener,
                            SurfaceHolder.Callback, Camera.PictureCallback { 

    private static final String TAG = "AppDebug";
    SurfaceView cameraView; 
    SurfaceHolder surfaceHolder; 
    Camera camera; 

    @SuppressWarnings("deprecation")
    @Override 
    public void onCreate(Bundle savedInstanceState)  { 
        super.onCreate(savedInstanceState); 

        setContentView(R.layout.cam_view); 

        cameraView = (SurfaceView) this.findViewById(R.id.CameraView); 

        surfaceHolder = cameraView.getHolder(); 
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
        surfaceHolder.addCallback(this); 

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

        cameraView.setOnClickListener(this); 
        Log.d(TAG,"before calling surfaceCreated");
        surfaceCreated(surfaceHolder);
        Log.d(TAG,"end of onCreate");
    } 

    public void onClick(View v) { 
        camera.takePicture(null, null, this); 
    } 

    public void onPictureTaken(byte[] data, Camera camera) { 
       Uri imageFileUri = 
          getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues()); 
        try { 
              OutputStream imageFileOS = 
                       getContentResolver().openOutputStream(imageFileUri); 
            imageFileOS.write(data); 
            imageFileOS.flush(); 
            imageFileOS.close(); 
        } catch (FileNotFoundException e) { 
            Toast t = Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT); 
            t.show(); 
        } catch (IOException e) { 
            Toast t = Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT); 
            t.show(); 
        } 
        camera.startPreview(); 
    } 

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
        camera.startPreview(); 
    } 

    public void surfaceCreated(SurfaceHolder holder) { 
        camera = Camera.open(); 

        try { 
            if(camera==null){
                throw new Exception("camera is null");
            }
            camera.setPreviewDisplay(holder); 
   } 
        catch (IOException exception) 
        { 
                      camera.release(); 
                      Log.d(TAG,exception.toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    } 

    public void surfaceDestroyed(SurfaceHolder holder) { 
           camera.stopPreview(); 
        camera.release(); 
    } 
} // End the Activity

And here's the AndroidManifest XML:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.camapp"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

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

</manifest>

Now I know that from above the problem lies in the surfaceChanged method, to be precise, the camera.startPreview which is the only piece of code in the method.

But I really don't see anything broken or wrong with it. Something definitely is null, but I don't know what.

3条回答
祖国的老花朵
2楼-- · 2019-07-31 17:06

Because camera is null, So just check if(camera != null) before camera.startPreview(); in surfaceChanged()

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
       if(camera == null) 
          camera = Camera.open();
          camera.startPreview(); 
} 
查看更多
祖国的老花朵
3楼-- · 2019-07-31 17:10

the camera instance is null in your onSurfaceChanged() method , you should verify if it is null , instanciate it , and then you can call startPreview() :

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
        if(camera == null)
           camera = Camera.open();
        camera.startPreview(); 
    } 
查看更多
我想做一个坏孩纸
4楼-- · 2019-07-31 17:21

You said that you were getting error on :

public void onClick(View v) { 
  camera.takePicture(null, null, this); 
}

in one of your comments.I too had this issue.Thats because the camera is having a null value at that moment.Modify your code as below:

public void onClick(View view) {
  if (camera != null) {
    Log.d("camera state","camera is NOT null");  
  }else{
    Log.d("camera state","camera is null");
    camera = android.hardware.Camera.open();
}
  camera.takePicture(null, null,new PhotoHandler(getApplicationContext()));
}

PS: I had the PhotoHandler class in my app,modify this as per your req.Hope it helps !

查看更多
登录 后发表回答