如何解决尝试忽略电话号码开头的零时出错?
//getting data
String _phoneNumber = number.getEditText().getText().toString().trim();
String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.charat(0) == '0') {
_phoneNumber = _phoneNumber.substring(1);
}
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.Stringindexoutofboundsexception: length=0; index=0
at java.lang.String.charat(Native Method)
解决方法
确保您的字符串不是空字符串。您可能对使用 startsWith()
方法而不是 charAt()
感兴趣:
String _phoneNumber = number.getEditText().getText().toString().trim();
String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.length > 0 && _phoneNumber.startsWith('0')) {
_phoneNumber = _phoneNumber.substring(1);
}
如果您有兴趣,这里是 startsWith()
文档的链接:https://developer.android.com/reference/java/lang/String#startsWith(java.lang.String)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。