java - parseInt 导致 android 应用程序崩溃

标签 java exception crash parseint value-of

我最终想把这个程序变成频率可调的频闪灯。但是,现在我只是想弄清楚基础知识。每次我使用 parseInt 应用程序崩溃。在此代码中,我在 strobe() 方法中使用它,但我尝试在其他地方使用它。我也试过用它来创建一个变量。它们都以相同的结果结束(应用程序崩溃)。谁能解释为什么会这样?

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

最佳答案

您需要 box1.getText(),而不是 box1.toString()


来自Android docs on toString() :

The default implementation is equivalent to the following expression:

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

这将(显然)不会返回可以解析为 Integer 的内容,从而创建您的 NumberFormatException。

关于java - parseInt 导致 android 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12256548/

相关文章:

java - 在每个 jvm 级别使用 == 运算符时,同一类的两个对象之间的明确比较是什么?

java - 使用自己的 Java 代码在 WEKA 中获取风险预测

c++ - 我什么时候应该真正使用 noexcept?

c++ - 自定义异常头文件

windows - Powershell 几个小时后崩溃

java - 比较器违反一般契约(Contract)

java - Java 中的数学矩阵

Javascript 源丢失

crash - 无法识别的选择器 +[AppDelegate count] - 应用程序在 NSPropertyListSerialization 调用时崩溃

python - py2exe 安装程序崩溃