尝试在空对象引用上调用虚拟方法 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()'
Posted
技术标签:
【中文标题】尝试在空对象引用上调用虚拟方法 \'android.view.SurfaceHolder android.view.SurfaceView.getHolder()\'【英文标题】:Attempt to invoke virtual method 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()' on a null object reference尝试在空对象引用上调用虚拟方法 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()' 【发布时间】:2019-04-15 01:38:15 【问题描述】:我将简单地使用相机生成录像机应用程序。但它崩溃并给我一个波纹管错误:
尝试调用虚方法 'android.view.SurfaceHolderandroid.view.SurfaceView.getHolder()' 空对象引用`
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_
android:layout_>
<ToggleButton
android:id="@+id/toggleRecordingButton"
android:layout_
android:textOff="Start Recording"
android:textOn="Stop Recording"
android:layout_
/>
<FrameLayout
android:layout_
android:layout_>
<SurfaceView android:id="@+id/surfaceView"
android:layout_
android:layout_></SurfaceView>
</FrameLayout>
</LinearLayout>
我已经阅读了所有的链接细节:
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
但对我没用。
【问题讨论】:
显示 activity_capture_video xml 文件 @Piyush 请检查我会更新.xml
代码看起来不错。只需清理您的项目并重新构建即可。
我也试试 Clear Project
, Rebuild Project
, Invalidate Caches / Restart
@Piyush
将 fill_parent
更改为 match_parent
。因为fill_parent
已被弃用。也通过这个link。还有
【参考方案1】:
我猜你正在关注一些教程视频或网站。如果没有,请立即执行。
检查以下事项。
-
检查所有主要表面视图、表面支架和相机的导入语句。
检查 xml 中的元素。
ctrl+点击R.id.surfaceView查看xml是否链接到java
【讨论】:
您的意思是,您检查了所有三个项目并且全部清除。但问题还是没有解决?如果是,请添加导入语句和完整的错误语句。 看看我会用导入文件更新我的问题 在surfaceCreated函数中替换行initRecorder(holder.getSurface());并初始化布尔值 mInitSuccesful=false; 你知道调试吗? 我尝试了所有的调试和所有的东西:)以上是关于尝试在空对象引用上调用虚拟方法 'android.view.SurfaceHolder android.view.SurfaceView.getHolder()'的主要内容,如果未能解决你的问题,请参考以下文章
尝试在空对象引用上调用虚拟方法 'android.graphics.Rect android.graphics.drawable.Drawable.getBounds()'
尝试在空对象引用上调用虚拟方法 'android.view.Window$Callback android.view.Window.getCallback()'
尝试在空对象引用上调用虚拟方法 'android.os.Handler android.support.v4.app.FragmentHostCallback.getHandler()'
尝试在空对象引用上调用虚拟方法 'void android.view.View.measure(int, int)'