Kenertj Kenertj - 1 month ago 12
Java Question

After checking if device supports flashlight, can't put boolean value inside if statement

I checked if device supports flash and I made an if statement, then I am getting an error. Does anyone know solution for this? It is saying that

hasFlash
is an unknown class.

import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageButton;


import static android.content.DialogInterface.*;

public class Flashlight extends AppCompatActivity {
private CameraManager cm;
private ImageButton flashlightButton;
private boolean flashlightOnOrOff;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
flashlightButton = (ImageButton) findViewById(R.id.flashOnOffButton);
flashlightOnOrOff = false;
}

//Error if device does not have flashlight
boolean hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
//This is where i get the error
if(hasFlash==false)

{
AlertDialog dialo = new AlertDialog.Builder(Flashlight.this).create();
dialo.setTitle("Error");
dialo.setMessage("Sorry your device does not have flashlight");
dialo.setButton(BUTTON_POSITIVE, "OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
dialo.show();


}




//What flashlight does on Stop
@Override
protected void onStop() {
super.onStop();
}

//What flashlight does on Pause
@Override
protected void onPause() {
super.onPause();
}

//What flashlight does on Resume
@Override
protected void onPostResume() {
super.onPostResume();
}


}

Answer

The code in question isn't in a function. Did you mean to put that in your onCreate? If so, your closing brace is in the wrong place:

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_flashlight);
    flashlightButton = (ImageButton) findViewById(R.id.flashOnOffButton);
    flashlightOnOrOff = false; 
} // REMOVE THIS 

//Error if device does not have flashlight 
    boolean hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    if(hasFlash==false)
    {
        AlertDialog dialo = new AlertDialog.Builder(Flashlight.this).create();
        dialo.setTitle("Error");
        dialo.setMessage("Sorry your device does not have flashlight");
        dialo.setButton(BUTTON_POSITIVE, "OK", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        dialo.show();
    }
} // THIS IS WHERE YOUR ONCREATE CLOSING BRACE GOES