0
我試圖做一個非常基本的手電筒應用程序。當用戶打開應用程序時,沒有佈局將被誇大,手電筒將打開。一旦用戶第二次打開手電筒將關閉。看起來好像打開手電筒並不麻煩,但在應用程序第二次啓動時將其關閉,這就是我有點不確定的地方。我不斷收到此錯誤:android手電筒第二次啓動錯誤
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;
}
}
}