[英]“Unfortunately app has stopped” when I want to convert the string to Long
I'm working on a very simple android code about a countdown timer , I used the android CountDownTimer class , so I want to get the millisInFuture (Long) from my editText , that's why I convert my string from this editText to a Long type (parseLong) , but when I try to run the app , it stopped. 我正在使用一个非常简单的有关倒数计时器的android代码,我使用了android CountDownTimer类,所以我想从editText获取millisInFuture(Long),这就是为什么我将字符串从此editText转换为Long类型( parseLong),但是当我尝试运行该应用程序时,它停止了。
public class MainActivity extends AppCompatActivity {
TextView tv;
Button btstop;
Button btstart;
EditText et;
Long mnt;
String strmnt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btstart=(Button) findViewById(R.id.xbtstart);
btstop=(Button) findViewById(R.id.xbtstop);
tv=(TextView) findViewById(R.id.xtv);
et=(EditText) findViewById(R.id.xet);
try {
mnt = Long.parseLong(strmnt);
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
final countD cdt= new countD(mnt,1000);
btstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cdt.start();
}
});
btstop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cdt.cancel();
}
});
}
public class countD extends CountDownTimer {
public countD(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long l) {
tv.setText("seconds remaining: " + l / 1000);
}
@Override
public void onFinish() {
tv.setText("done!");
}
}
} }
I/System.out: parse value is not valid : java.lang.NumberFormatException: Invalid long: "null"
Move the parsing part inside the onClick
method. 将解析部分
onClick
方法中。 Use some validations on the entered value as shown below. 如下所示对输入的值进行一些验证。
Try this code, 试试这个代码,
btstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String strmnt = et.getText().toString();
if(strmnt.length() > 0){
try {
mnt = Long.parseLong(strmnt);
final countD cdt= new countD(mnt,1000);
cdt.start();
} catch(NumberFormatException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "Please fill the field", Toast.LENGTH_LONG).show();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.