NullPointerException in setPreviewDisplay (owner)

Pretty new on this Android stuff and gets a NullPointException, which I cannot understand. I am trying to implement the onResume () method in my CameraActivity and have moved almost all the source code in onCreate () to onResume () and then will call onResume () in onCreate (). The activity worked fine when the code was in onCreate (), but when placed in onResume () the exception was arsises. What causes this?

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 } } 

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

Cat Log:

 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) 
+4
source share
3 answers

The solution was to call the getCameraInstancemethod () method in onResume () in the if-statement

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

I think your problem is here.

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

this.mCamera seems to be null, it should not be installed by a new instance of the class, this must be done in the getCameraInstance () method.

+1
source

getCameraInstance() returns null if an exception is thrown. This causes the NPE as this.mCamera null .

You should check if the exception was thrown in getCameraInstance and handle it correctly. The most important thing is to register it and try to understand the reason.

0
source

Source: https://habr.com/ru/post/1481953/


All Articles