什么是IndexOutOfBoundsException?我该如何解决? [英] What is IndexOutOfBoundsException? How can I fix it?

查看:387
本文介绍了什么是IndexOutOfBoundsException?我该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

    private void bringData() {
    final TextView mTextView = (TextView) findViewById(R.id.textView);

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://192.168.4.1:8080/";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    mTextView.setText("Response is: "+ response.substring(0,500));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

这是android文档中给出的默认值。我只更改了网址。

It's the default given from the android documentation. I only changed the url.

这是我的错误信息:


java.lang.StringIndexOutOfBoundsException:length = 28; regionStart = 1;
regionLength = 499
at java.lang.String.substring(String.java:1931)
at com.example.my.app.MainActivity $ 2.onResponse(MainActivity.java:50)
at com.example.my.app.MainActivity $ 2.onResponse(MainActivity.java:46)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery $ ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android。 os.Handler.handleCallback(Handler.java:751)
在android.os.Handler.dispatchMessage(Handler.java:95)
在android.os.Looper.loop(Looper.java:154)
在android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:755)

java.lang.StringIndexOutOfBoundsException: length=28; regionStart=1; regionLength=499 at java.lang.String.substring(String.java:1931) at com.example.my.app.MainActivity$2.onResponse(MainActivity.java:50) at com.example.my.app.MainActivity$2.onResponse(MainActivity.java:46) at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

在调试过程中,我看到 mTextView.setText (响应是:+ response.substring(0,500)); 我的消息已发送给我,但textview永远不会更新,应用程序崩溃。

During debugging I see that at mTextView.setText("Response is: "+ response.substring(0,500)); my message is delivered to me but the textview is never updated and the app crashes.

具体来说,它在Looper.Java文件中崩溃:

Specifically, it crashes here inside the Looper.Java file:

finally {
if (traceTag != 0) {
   Trace.traceEnd(traceTag);
} 

traceTag为0.

traceTag is 0.

我读到一些字符串边界是错误的,但我找不到如何解决它。

I read that some string bounds are wrong but I cannot find out how to fix it.

推荐答案

Error Message:
    java.lang.StringIndexOutOfBoundsException: length=28; regionStart=1;
    regionLength=499 at java.lang.String.substring(String.java:1931) at     
    com.example.my.app.MainActivity$2.onResponse(MainActivity.java:50) at     
    com.example.my.app.MainActivity$2.onResponse(MainActivity.java:46) at     
    com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) at     
    com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) at     
    com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) at android.os.Handler.handleCallback(Handler.java:751) at     
    android.os.Handler.dispatchMessage(Handler.java:95) at     
    android.os.Looper.loop(Looper.java:154) at     
    android.app.ActivityThread.main(ActivityThread.java:6077) at     
    java.lang.reflect.Method.invoke(Native Method) at     
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at     
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

错误说明

There is an IndexOutOfBound exception occurred in your MainActivity class 
Inside second inner class's OnResponse function as shown MainActivity$2onResponse
on line 46 which basically occurred during substring operation in String.java line 1931 
which was invoked from StringRequest.deliverResponse at line 60,
which was invoked from StringRequest.deliverResponse at line 30,
which was invoked from ExecutorDelivery.java at line 99,
which intially started from ZygoteInit$MethodAndArgsCaller's run function 
and reached up-to main thread of ActivityThread.main=>looper=>handler

实际原因

您的代码尝试使用

starting index = 0
ending index = 500

虽然哟你的实际响应字符串长度是= 28,所以字符串长度不足以创建500个字符的子字符串。

though your actual response string length is = 28, so String length is not long enough to create a substring of 500 characters.

解决方案:


  1. 使用三元运算符验证长度?:

mTextView.setText("Response is: "+ 
   ((response.length()>499) ? response.substring(0,500) : "length is too short"));

注意:三元运算符(?:)是 if else 的简短表达,但它是 not a statement 意味着它不能作为原子语句出现,因为这是 INVALID 因为没有作业

Note : Ternary operator (?:) is a short expression of if else but it is not a statement mean it cannot occur as an atomic statement as this is INVALID because there is no assignment

((someString.length()>499) ? someString.substring(0,500):"Invalid length");


  • if-else 增强了可见性

    String msg="Invalid Response";
    if(response.length()>499){
        msg=response.substring(0,500);
    }
    mTextView.setText("Response is: "+msg);
    
    //or     mTextView.setText("Response is: "+response);
    




  • 什么是IndexOutOfBoundsException?



    What is IndexOutOfBoundsException?


    IndexOutOfBoundsException 的子类RuntimeException mean
    它是一个未经检查的异常,它被抛出以指示某种索引
    (例如数组,字符串或向量)超出
    of range.eg使用List。

    IndexOutOfBoundsException is a subclass of RuntimeException mean it is an unchecked exception which is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.e.g using List.

    ,如文档


    List<String> ls=new ArrayList<>();
          ls.add("a");
          ls.add("b");
          ls.get(3); // will throw IndexOutOfBoundsException , list length is 2
    


    预防

    String str = "";
    int index =3; 
    if(index < ls.size())    // check, list size must be greater than index
        str = ls.get(index);
    else
        // print invalid index or other stuff
    



    类构造函数用法索引或字符串消息



    Class Constructor usage with index or string message

    public IndexOutOfBoundsException() {
        super();
    }
    
    public IndexOutOfBoundsException(String s) {
        super(s);
    }
    



    哪些是IndexOutOfBoundsException的其他变体/子类?




    • ArrayIndexOutOfBoundsException :这表示已使用非法索引访问了数组。索引是负数或大于或等于数组的大小,例如

      Which are other variations/sub-classes of IndexOutOfBoundsException?

      • ArrayIndexOutOfBoundsException : This indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array for e.g


        int arr = {1,2,3}
        int error = arr[-1]; // no negative index allowed
        int error2 = arr[4]; // arr length is 3 as index range is 0-2
        



      • 预防

        int num = "";
        int index=4;
        if(index < arr.length)     // check, array length must be greater than index
            num = arr[index];
        else
            // print invalid index or other stuff
        




        • StringIndexOutOfBoundsException :这是String方法抛出的,表示索引是负数或大于字符串的大小。对于某些方法(如charAt方法),当索引等于字符串的大小时,也会抛出此异常。

          • StringIndexOutOfBoundsException : This is thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.


            String str = "foobar";       // length = 6
            char error = str.charAt(7);  // index input should be less than or equal to length-1
            char error = str.charAt(-1); // cannot use negative indexes
            



          • 预防

            String name = "FooBar";
            int index = 7;
            char holder = '';
            if(index < name.length())     // check, String length must be greater than index
                holder = name.charAt(index) ;
            else
                // print invalid index or other stuff
            

            注意: length() String class和 length 数组的关联字段

            Note: length() is a function of String class and length is a associative field of an array.


            • 使用负数索引数组 charAt substring functions

            • BeginIndex小于 0 或endIndex是大于要创建的输入字符串的长度 substring 或beginIndex大于endIndex

            • endIndex时 - beginIndex 结果小于 0

            • 输入字符串/数组为空时

            • Usage of Negative index with arrays or charAt , substring functions
            • BeginIndex is less than 0 or endIndex is greater than the length of input string to create substring or beginIndex is larger than the endIndex
            • When endIndex - beginIndex result is less than 0
            • When input string/array is empty

            INFO:创建适当异常的对象并将其传递到使用它的位置是JVM的工作抛出关键字,或者您也可以使用<$ c手动执行此操作$ c>抛出关键字。

            INFO : It is job of JVM to create the object of appropriate exception and pass it to the place of , where it occurred using throw keyword like or you can also do it manually using throw keyword too.

            if (s == null) {
                throw new IndexOutOfBoundsException("null");
            }
            



            我该如何解决这个问题?



            How can I fix this ?


            1. 分析StackTrace

            2. 根据无效,长度或有效索引验证输入字符串

            3. 使用调试或日志

            4. 使用Generic Exception catch块

            1. Analyzing StackTrace
            2. Validating input string against nullity , length or valid indexes
            3. Using Debugging or Logs
            4. Using Generic Exception catch block



            1。)分析StackTrace



            如本文开头所示,stacktrace在初始消息中提供了有关其发生位置的必要信息,为什么会发生这种情况,因此您只需跟踪该代码并应用所需的解决方案。

            1.) Analyzing StackTrace

            As shown at the beginning of this post , stacktrace provides the necessary information in the initial messages about where it happen , why it happen so you can simply trace that code and apply the required solution .

            例如 StringIndexOutOfBoundsException 的原因,然后查找指示您的类文件的包名称然后转到该行并记住原因,只需应用解决方案

            for e.g the reason StringIndexOutOfBoundsException and then look for your package name indicating your class file then go to that line and keeping the reason in mind , simply apply the solution

            如果您研究异常及其原因,这是一个良好的开端很好的文档。

            It's a head start if you study about the exception and its cause as well in documentation.

            如果您不知道实际输入,例如响应来自服务器(或者可能是错误或什么都没有)或用户那么不确定覆盖所有意外情况总是更好虽然相信我很少有用户总是喜欢突破测试的极限所以使用输入!= null&& input.length()> 0 或对于索引,您可以使用三元运算符或 if-else 边界检查条件

            In case of uncertainty when you don't know about the actual input like response is coming from server (or maybe it's an error or nothing) or user then it's always better to cover all the unexpected cases though believe me few users always like to push the limits of testing so use input!=null && input.length()>0 or for indexes, you can use the ternary operator or if-else boundary check conditions

            您可以通过在调试模式中添加断点来测试项目的运行环境您的项目和系统将停在那里等待您的下一个操作,同时您可以查看变量和其他详细信息的值。

            You can test the running environment of your project in debug mode by adding break-points in your project and system will stop there to wait for your next action and meanwhile you can look into the values of variables and other details.

            日志就像检查点所以当您的控制跨越这一点时,它们会生成详细信息,基本上它们是由枯萎系统提供的信息性消息,或者用户也可以使用Logs或Println消息放置日志消息

            Logs are just like check-points so when your control cross this point they generate details , basically they are informative messages given by wither system or user can also put logging messages using either Logs or Println messages

            try-catch 块总是有用处理 RuntimeExceptions 因此您可以使用多个 catch 块来处理您可能出现的问题并提供相应的详细信息

            Try-catch blocks are always useful to handle RuntimeExceptions so you can use multiple catch block along to handle your possible issues and to give appropriate details

            try {
                 mTextView.setText("Response is: "+ response.substring(0,500));
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
                System.out,println("Invalid indexes or empty string");
            }
              catch (NullPointerException e) { // mTextView or response can be null 
                e.printStackTrace();
                System.out,println("Something went wrong ,missed initialization");
            }
            catch (Exception e) {  
                e.printStackTrace();
                System.out,println("Something unexpected happened , move on or can see stacktrace ");
            }
            

            其他参考资料

            什么是NullPointerException ,我该如何解决?

            这篇关于什么是IndexOutOfBoundsException?我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆