Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt causes android app to crash

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();
}

}

like image 800
user1644985 Avatar asked Dec 30 '25 06:12

user1644985


1 Answers

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.

like image 186
Jon Newmuis Avatar answered Jan 01 '26 06:01

Jon Newmuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!