android手电筒第二次启动错误

里法特·拉希德(RifatRashid)

我正在尝试制作一个非常基本的手电筒应用程序。当用户打开应用程序时,不会放大任何布局,手电筒只会打开。一旦用户第二次打开手电筒,手电筒将关闭。似乎打开手电筒不是一件容易的事,但是当应用程序第二次启动时要关闭它,那有点不确定。我不断收到此错误:

Process: com.example.rifatrashid.lighter, PID: 16558
        java.lang.RuntimeException: Unable to resume activity        {com.example.rifatrashid.lighter/com.example.rifatrashid.lighter.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera$Parameters.setFlashMode(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2951)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2982)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera$Parameters.setFlashMode(java.lang.String)' on a null object reference
        at com.example.rifatrashid.lighter.MainActivity.onResume(MainActivity.java:33)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1241)
        at android.app.Activity.performResume(Activity.java:6019)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2940)

            

public class MainActivity extends Activity {
private boolean haslight;
private Integer val = 0;
private Camera camera;
private Camera.Parameters parameters;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
haslight = getApplicationContext().getPackageManager().hasSystemFeature((PackageManager.FEATURE_CAMERA_FLASH));
if(!haslight) {

}
camera = Camera.open();
parameters = camera.getParameters();
val++;
if(val>1)
    val=0;
switch (val){
    case 1:
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.startPreview();
        break;
    case 0:
        camera.stopPreview();
        camera.release();
        break;
}
}
}
马蒂亚·梅斯特里尼(Mattia Maestrini)

堆栈跟踪表明您尝试在空对象引用上调用setFlashMode。您需要先检查参数是否为空:

if (parameters != null)
    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章