Faizah Fairooz
Faizah Fairooz

Reputation: 23

App takes binary Input from user and blinks flashlight transmitting the input when a button is pressed in Android Studio

SO i am trying to create an app that transmits the user input through blinking flash light. When i use a fixed String myString = "1010101" the flashlight blinks so my app is able to access the flashlight. However, when i take an input from the user and save it in String myString, i press the button but nothing happens. For now i only want to take binary input. Please Help me out.

EditText binData;
Button blinkMode;
boolean isFlashOn = false;
Camera camera;
String myString;

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

    binData = (EditText)findViewById(R.id.editText);
    final Camera.Parameters params = camera.getParameters();
    blinkMode = (Button)findViewById(R.id.button);

    myString = binData.getText().toString();

    blinkMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            long blinkDelay = 50; //Delay in ms
            for(int i=0; i<myString.length(); i++){
                if(myString.charAt(i)=='1'){
                    params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    camera.setParameters(params);
                    camera.startPreview();
                    isFlashOn = true;


                } else if(myString.charAt(i)=='0') {

                    params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    camera.setParameters(params);
                    camera.stopPreview();
                    isFlashOn = false;

                }
                try {
                    Thread.sleep(blinkDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            int length=myString.length();
            if(length == myString.length() ) {
                params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(params);
                camera.stopPreview();
                isFlashOn = false;
            }
        }
    });
}

Upvotes: 2

Views: 213

Answers (1)

not_again_stackoverflow
not_again_stackoverflow

Reputation: 1323

Move this line

myString = binData.getText().toString();  

inside the onClick() method. That should ideally fix your issue. You are accessing the string before the button click is made. My guess is that empty string was being taken so far.

Upvotes: 1

Related Questions