简体   繁体   中英

Toggle Button is crashing the android app

I have been developing a simple flash light app, it works but there is only one problem, when i click the toggle button it switches the light on, but when i click on again the app crashes...

package com.example.flashapp;

import android.hardware.Camera;
import android.os.Bundle;
import android.app.*;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

ToggleButton toggleButton;
Camera camera;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toggleButton = (ToggleButton)findViewById(R.id.onOffFlashlight);

    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton,boolean checked) {
                //ToDo something
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                camera.startPreview();
                Toast.makeText(getApplicationContext(), "Flash Light is ON", Toast.LENGTH_LONG).show();
        }
    });

}

}

You should always post the crash log when reporting a crash here. But in this case I actually can tell you why- since you never release the camera, the second time you call Camera.open() it returns null, and you crash with an NPE. You should always release the camera when done with it, and you need to code for the case where you can't get the camera for whatever reason (another app may be using it).

Also, your checkbox is always grabbing the camera- there's no way to toggle it to off, you only coded the on case.

Changed to like this

toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton,boolean checked) {

            if (isChecked) {
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                camera.startPreview();
                Toast.makeText(getApplicationContext(), "Flash Light is ON", Toast.LENGTH_LONG).show();   
            }
            else {
                  // Code to switch off Flashlight
            }   

    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM