如何在Android中解析StringIndexOutOfBoundsException

2022-09-04 21:11:22

这是我的 logcat 报告:

java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=2
at java.lang.String.startEndAndLength(String.java:583)
at java.lang.String.substring(String.java:1464)
at com.buzzador.profile.getValidPhoneNumber(profile.java:1966)
at com.buzzador.profile.setDataForServer(profile.java:1717)
at com.buzzador.profile$5.onClick(profile.java:236)
at android.view.View.performClick(View.java:4377)
at android.view.View$PerformClick.run(View.java:18044)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5306)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)

我认为问题出在此功能中:

public String getValidPhoneNumber (String phoneNumber, String country)
{
    String csValidPhoneNumber = "";

    phoneNumber = getPhoneNumberWithoutReqularExpresions(phoneNumber);
    phoneNumber = phoneNumber.replaceFirst ("^0*", "");

    String csCountryCode = getCountryCode(country);

    String csAppendedCode = phoneNumber.substring(0, csCountryCode.length());
    if(csAppendedCode.equals(csCountryCode))
    {
        csValidPhoneNumber = "+" + phoneNumber;
        return csValidPhoneNumber;
    }

    csValidPhoneNumber = "+" + csCountryCode + phoneNumber;

    return csValidPhoneNumber;
}

答案 1

你确定不等于吗?您必须检查是否具有比 .phoneNumber""phoneNumbercsCountryCode.length()

String csAppendedCode = phoneNumber.length() > csCountryCode.length() ? phoneNumber.substring(0, csCountryCode.length()) : "";

答案 2

的最后一个索引是,但您正在尝试访问不存在的索引,这就是为什么您得到此异常的原因...Stringstring.length()-1string.length()

java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=2

现在,您应该更改此行...

String csAppendedCode = phoneNumber.substring(0, csCountryCode.length());

到这个...

String csAppendedCode = phoneNumber.substring(0, csCountryCode.length()-1);

推荐