单击带有空 editText 的按钮时应用程序崩溃
btnNadoplata.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
if (text1.getText().length() == 14 ) {
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}else {
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
}
}
});
我有一个 editText,用户需要在其中输入一个 14 位数字。如果数字小于或大于 14 位,当用户单击按钮时,他会收到一条消息,提示输入不好。问题是当 editText 为空并且用户单击按钮时,应用程序崩溃。我怎样才能改变这个,所以如果editText为空,用户从上面的代码部分获取消息?
抱歉我的英语不好。
btnNadoplata.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
if (text1.getText().length() == 14 ) {
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}else {
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
}
}
});
I have one editText, in wich user needs to input a number14 digit number. If number is less or more than an 14 digits, when user clikc on button, he gets the message that say input is not good. The problem is when editText is empty, and user click on button, app crashes. how can i change this, so if editText is empty, user gets message from above code part ??
Sory for my bad english.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能会在这一行崩溃:
事实上,如果您的 EditText
text1
中有一个空字符串,则函数parseLong()
将抛出NumberFormatException
> 例外。在继续之前,您应该测试
text1
的文本值:或者您可以添加
try/catch
指令来捕获Long.parseLong()< 抛出的异常/代码>。
It might crash on this line:
In fact, if you have an empty string in your EditText
text1
, the functionparseLong()
will throw aNumberFormatException
exception.You should test the value of the text of
text1
before continuing:Or you can add
try/catch
instruction to catch the exception thrown byLong.parseLong()
.您应该在解析之前测试您的输入长度。解析崩溃。
另一种方法可能是用 try/catch/block 包围解析,但它的效率比这个简单的测试低,但如果用户输入非数字,则更稳健。
问候,
史蒂芬
You should test your input length before parsing. Parsing crashes.
An alternative could be to surround parsing with a try/catch/block, but it's less efficient than this simple test, but more robust if user types non digits.
Regards,
Stéphane