how to resolve StringIndexOutOfBoundsException in android

落花浮王杯 提交于 2019-12-10 12:39:33

问题


This is my logcat report:

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)

and i think the issue is in this function:

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:


Are you sure that phoneNumber is not equal to ""? You have to check that phoneNumber have more chars than the csCountryCode.length().

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



回答2:


The last index of a String is string.length()-1 but you are trying to access index with string.length() which doesn't exist, that's why you are getting this exception...

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

Now, you should change this line...

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

to this...

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


来源:https://stackoverflow.com/questions/22955414/how-to-resolve-stringindexoutofboundsexception-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!