我有一个具有Tablayout + Viewpager组合的活动,它们一起托管了四个片段,其中一个片段是我使用Intent打开相机并在那里解析结果。
有时我在onActivityResults上解析结果时,我会得到NullPointerException
这是代码
public class CheckInFragment extends BaseFragment implements CheckInPresenterView {
private CameraIntegrator cameraIntegrator;
private ImageCallback cameraResultCallback = new ImageCallback() {
@Override
public void onResult(int requestedBy, Result result) {
if (requestedBy == RequestSource.SOURCE_CAMERA) {
...
}
}
};
private void openCamera() {
// Permission Check Shifted To Attendance Activity
if (cameraIntegrator == null) {
cameraIntegrator = new CameraIntegrator(this);
cameraIntegrator.setImageDirectoryName(GlobalConstants.IMAGE_FOLDER_NAME);
cameraIntegrator.setRequiredImageSize(ImagesSizes.OPTIMUM_MEDIUM);
}
try {
cameraIntegrator.initiateCapture();
} catch (NoCameraAppFoundException e) {
e.printStackTrace();
}
}
@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CameraIntegrator.REQUEST_IMAGE_CAPTURE)
cameraIntegrator.parseResults(requestCode, resultCode, data, cameraResultCallback); //Null Pointer Exception here sometimes
}
}
}
Crashlytics日志:
Fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.xxx.AttendanceActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {com.xxx.AttendanceActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.xxx.CameraIntegrator.parseResults(int, int, android.content.Intent, com.xxx.camera.ImageCallback)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3513)
有人可以解释为什么有时我会使用cameraIntegrator null
吗?
是因为此代码在家长活动中吗?
ViewPagerGeneralAdapter viewPagerAdapter = setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(viewPagerAdapter.getCount()); <---
我该如何重现此错误?
答案 0 :(得分:0)
改为在片段cameraIntegrator
方法中初始化onResume()
。问题是,如果重新创建了片段(例如,从其他活动返回时),则可能不会调用您的openCamera()
方法,因此cameraIntegrator
将永远不会初始化,并且为空。 / p>
尝试一下。
@override
public void onResume(){
super.onResume();
initializeCameraIntegrator();
}
private void initializeCameraIntegrator(){
if (cameraIntegrator == null) {
cameraIntegrator = new CameraIntegrator(this);
cameraIntegrator.setImageDirectoryName(GlobalConstants.IMAGE_FOLDER_NAME);
cameraIntegrator.setRequiredImageSize(ImagesSizes.OPTIMUM_MEDIUM);
}
}
private void openCamera() {
try {
cameraIntegrator.initiateCapture();
} catch (NoCameraAppFoundException e) {
e.printStackTrace();
}
}