InputFilter中的IndexOutOfBoundsException

时间:2014-10-18 15:51:04

标签: java android indexoutofboundsexception input-filter

在一些Android设备上,我在InputFilter中得到了一个IndexOutOfBoundsException,我在输入开头就删除了任何零:

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)});

堆栈跟踪:

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)

1 个答案:

答案 0 :(得分:1)

在访问其中的任何字符之前,您必须检查该源是否为空。

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