Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

java - getting error while try to ignore zero at the begining of phonenumber?

//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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Make sure your string is not an empty string. You may be interested in using the startsWith() method instead of 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);
}

Here is a link to the startsWith() docs, if you're interested: https://developer.android.com/reference/java/lang/String#startsWith(java.lang.String)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...