javaandroidindexoutofboundsexceptioninput-filter

IndexOutOfBoundsException inside InputFilter


On some android devices I got an IndexOutOfBoundsException inside an InputFilter that I used to remove any zeros at the start of the input:

MyCode:

    zeroFilter = new InputFilter()
    {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
        {
            if(dest.length() == 0)
            {
                if (source.charAt(0) == '0')
                {
                    return ""; 
                } 
            }
                return null;
        } 
    };

    etxtNumbers.setFilters(new InputFilter[]{zeroFilter, new InputFilter.LengthFilter(5)});

StackTrace:

java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:111)
at com.nasseralsalmi.wheel.AddPrivatePlateActivity$1.filter(AddPrivatePlateActivity.java:57)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:428)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:420)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:29)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:667)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:425)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:333)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
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:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)

Solution

  • You must check that source is not empty before accessing any character in it.

    if (source.length() > 0 && source.charAt(0) == '0')
    {
        return ""; 
    }