android手电筒第二次启动错误

时间:2015-04-12 06:00:40

标签: android flashlight

我试图制作一个非常基本的手电筒应用程序。当用户打开应用程序时,没有布局会膨胀,手电筒将打开。一旦用户第二次打开手电筒,手电筒将关闭。似乎打开手电筒并不麻烦,但是当应用程序第二次启动时将其关闭,这就是我有点不确定的地方。我一直收到这个错误:

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

1 个答案:

答案 0 :(得分:1)

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

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