title: Android flashlight app, can turn light on but not off
body: <p>Just getting into Android programming and this is my first app. It is essentially a toggle button which turns the light on or off. The app loads fine, if I press the button it turns on fine, however if I turn it off while it is on I get "App has stopped working" message and it closes. </p>
  
  <p>Can someone point where I'm going wrong? Thanks</p>
  
  <pre><code>public class MainActivity extends ActionBarActivity {
  int flag = 0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
  
      final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
      button.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
  
  
              EditText editText = (EditText) findViewById(R.id.editText);
  
              if (flag==0) {
                  flag=1;
                  editText.setText("ON");
                  Camera camera = Camera.open();
                  Camera.Parameters p = camera.getParameters();
                  p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                  camera.setParameters(p);
                  camera.startPreview();
  
              }
              else {
                  if (flag == 1) {
                      flag = 0;
                      editText.setText("OFF");
                      Camera camera = Camera.open();
                      Camera.Parameters p = camera.getParameters();
                      p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                      camera.setParameters(p);
                      camera.stopPreview();
                  }
              }
              }
  
  
  
      });
  
  
  }
  
  
  }
  </code></pre>