3

I eventually want to turn this program into a strobe light wih an adjustable frequency. However, right now I'm just trying to get the basics worked out. Everytime I use parseInt the app crashes. In this code i use it in the strobe() method, but I have tried using it in other places. I have also tried to use it to create a variable. They all end in the same result (the app crashes). Can anyone explain why this happens?

EditText box1, box2;
Button toggle;
int firstNum;
String string1;
Camera cam;


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

    makeVariables();

    toggle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            strobe();
            }
    });

}

private void  makeVariables(){
    box1 = (EditText)findViewById(R.id.editText1);
    box2 = (EditText)findViewById(R.id.editText2);
    string1 = box1.toString();
    string2 = box2.toString();
    toggle = (Button)findViewById(R.id.button1);
}

private void turnOnLight(){
    cam = Camera.open();
    Parameters params = cam.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
    cam.setParameters(params);
    cam.startPreview();
    cam.autoFocus(new AutoFocusCallback(){
        public void onAutoFocus(boolean success, Camera camera) {
        }

    });
}
private void turnOffLight(){
    cam.stopPreview();
    cam.release();
}
private void strobe(){
    Thread timer = new Thread(){
        public void run(){
            turnOnLight();
            try{
                    sleep(Integer.ParseInt(box1.toString()));
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
                turnOffLight();
                    }
                }
        };
    timer.start();
}

}

Adam
  • 35,919
  • 9
  • 100
  • 137

2 Answers2

2

You want box1.getText(), not box1.toString().


From the Android docs on toString():

The default implementation is equivalent to the following expression:

getClass().getName() + '@' + Integer.toHexString(hashCode())

This will (clearly) not return something that can be parsed to an Integer, thus creating your NumberFormatException.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0

You need to handle the NumberFormatException that happens if the input field is empty, or not a number.

Also you should use getText() rather than toString(). The toString() methods usually return something like "EditText@70AF5" which is causing the uncaught NumberFormatException, and ultimately your app to crash.

try {
    sleep(Integer.parseInt(box1.getText()));
} catch (NumberFormatException e) {
  // do something else, or nothing at all.
}
Adam
  • 35,919
  • 9
  • 100
  • 137