Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to invoke virtual method 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()' on a null object reference

i'll be simply generate video recorder application using Camera. but it's crash and give me a bellow error :

Attempt to invoke virtual method 'android.view.SurfaceHolderandroid.view.SurfaceView.getHolder()' on a null object reference`

Capture Video Activity.class

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

    public class CaptureVideoActivity extends Activity implements SurfaceHolder.Callback {

        private MediaRecorder mMediaRecorder;
        private Camera mCamera;
        private SurfaceView mSurfaceView;
        private SurfaceHolder mHolder;
        private View mToggleButton;
        private boolean mInitSuccesful;
        CameraCharacteristics characteristics;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_capture_video);

            // we shall take the video in landscape orientation
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
            mHolder = mSurfaceView.getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

            mToggleButton = (ToggleButton) findViewById(R.id.toggleRecordingButton);
            mToggleButton.setOnClickListener(new View.OnClickListener() {
                @Override
                // toggle video recording
                public void onClick(View v) {
                    if (((ToggleButton) v).isChecked()) {
                        mMediaRecorder.start();
                        try {
                            Thread.sleep(7 * 1000); // This will recode for 10 seconds, if you don't want then just remove it.
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //finish();
                    } else {
                        mMediaRecorder.stop();
                        mMediaRecorder.reset();
                        try {
                            initRecorder(mHolder.getSurface());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        /* Init the MediaRecorder, the order the methods are called is vital to
         * its correct functioning */
        private void initRecorder(Surface surface) throws IOException {
            // It is very important to unlock the camera before doing setCamera
            // or it will results in a black preview
            if (mCamera == null) {
                mCamera = Camera.open();
                mCamera.unlock();
            }

            if (mMediaRecorder == null) mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setPreviewDisplay(surface);
            mMediaRecorder.setCamera(mCamera);

            File file = getOutputMediaFile(2);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            //       mMediaRecorder.setOutputFormat(8);
           // mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setOutputFile(file.getAbsolutePath());
            mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
            /*mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
            mMediaRecorder.setVideoFrameRate(30);
            mMediaRecorder.setVideoSize(640, 480);*/
            int deviceorientation = getResources().getConfiguration().orientation;
            mMediaRecorder.setOrientationHint(getJpegOrientation(characteristics, deviceorientation));

            try {
                mMediaRecorder.prepare();
            } catch (IllegalStateException e) {
                // This is thrown if the previous calls are not called with the
                // proper order
                e.printStackTrace();
            }

            mInitSuccesful = true;
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                if (!mInitSuccesful)
                    initRecorder(mHolder.getSurface());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            shutdown();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        private void shutdown() {
            // Release MediaRecorder and especially the Camera as it's a shared
            // object that can be used by other applications
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mCamera.release();

            // once the objects have been released they can't be reused
            mMediaRecorder = null;
            mCamera = null;
        }

        private static File getOutputMediaFile(int type){
            // To be safe, you should check that the SDCard is mounted
            // using Environment.getExternalStorageState() before doing this.

            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES), "Test Capture");
            // This location works best if you want the created images to be shared
            // between applications and persist after your app has been uninstalled.

            // Create the storage directory if it does not exist
            if (! mediaStorageDir.exists()){
                if (! mediaStorageDir.mkdirs()){
                    Log.d("MyCameraApp", "failed to create directory");
                    return null;
                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File mediaFile;
            if (type == MEDIA_TYPE_IMAGE){
                mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                        "IMG_"+ timeStamp + ".jpg");
            } else if(type == MEDIA_TYPE_VIDEO) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                        "VID_"+ timeStamp + ".mp4");
            } else {
                return null;
            }

            return mediaFile;
        }

        private int getJpegOrientation(CameraCharacteristics c, int deviceOrientation) {
            if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN)
                return 0;
            int sensorOrientation = c.get(CameraCharacteristics.SENSOR_ORIENTATION);

            // Round device orientation to a multiple of 90
            deviceOrientation = (deviceOrientation + 45) / 90 * 90;

            // Reverse device orientation for front-facing cameras
            boolean facingFront = c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT;
            if (facingFront) deviceOrientation = -deviceOrientation;

            // Calculate desired JPEG orientation relative to camera orientation to make
            // the image upright relative to the device orientation
            return (sensorOrientation + deviceOrientation + 360) % 360;

        }
    }

activity_capture_video.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ToggleButton
        android:id="@+id/toggleRecordingButton"
        android:layout_width="fill_parent"
        android:textOff="Start Recording"
        android:textOn="Stop Recording"
        android:layout_height="wrap_content"
        />
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <SurfaceView android:id="@+id/surfaceView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"></SurfaceView>

    </FrameLayout>
</LinearLayout>

i have already read all the link details :

  • How to solve "android.view.SurfaceView.getHolder()' on a null object reference"?

  • 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()' on a null object reference in SurfaceView

  • surfaceView.getHolder not returning SurfaceHolder

but not useful for me.

like image 472
Sandeep Patel Avatar asked Nov 08 '22 00:11

Sandeep Patel


1 Answers

I guess you were following some tutorial video or website. If not please do it now.

Check the following things.

  1. Check the import statements for all mainly surfaceview, surfaceholder and camera.
  2. Check the elements in xml.
  3. Check whether the xml is linked to java by ctrl+click on R.id.surfaceView
like image 152
Bala555 Avatar answered Nov 11 '22 17:11

Bala555