我最终想把这个程序变成频率可调的频闪灯。但是,现在我只是想弄清楚基础知识。每次我使用 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/