什么是IndexOutOfBoundsException?我该如何解决?

tra*_*ler 7 java android android-volley

这是我的代码:

    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);
}
Run Code Online (Sandbox Code Playgroud)

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

这是我的错误消息:

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

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

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

finally {
if (traceTag != 0) {
   Trace.traceEnd(traceTag);
} 
Run Code Online (Sandbox Code Playgroud)

traceTag为0.

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

Pav*_*ngh 13

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) 
Run Code Online (Sandbox Code Playgroud)

错误说明

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
Run Code Online (Sandbox Code Playgroud)

实际原因

您的代码尝试使用创建子字符串

starting index = 0
ending index = 500
Run Code Online (Sandbox Code Playgroud)

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

方案:

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

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

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

    ((someString.length()>499) ? someString.substring(0,500):"Invalid length");
    
    Run Code Online (Sandbox Code Playgroud)
  2. 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);
    
    Run Code Online (Sandbox Code Playgroud)

什么是IndexOutOfBoundsException?

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

文档中所示

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

预防:

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
Run Code Online (Sandbox Code Playgroud)

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

public IndexOutOfBoundsException() {
    super();
}

public IndexOutOfBoundsException(String s) {
    super(s);
}
Run Code Online (Sandbox Code Playgroud)

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

预防:

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
Run Code Online (Sandbox Code Playgroud)
  • StringIndexOutOfBoundsException:String方法抛出此操作以指示索引为负数或大于字符串的大小.对于某些方法(如charAt方法),当索引等于字符串的大小时,也会抛出此异常.

    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
    
    Run Code Online (Sandbox Code Playgroud)

预防:

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
Run Code Online (Sandbox Code Playgroud)

注意: length()String类的函数,length是一个关联字段array.

为什么会发生这种异常

  • 具有负指数的使用arrayscharAt,substring功能
  • BeginIndex小于0或者endIndex大于要创建的输入字符串的长度substring 或者beginIndex大于endIndex
  • endIndex - beginIndex结果小于0
  • 当输入字符串/数组为空时

信息: JVM的工作是创建适当异常的对象并将其传递到使用throw关键字之类的地方,或者也可以使用throw关键字手动执行.

if (s == null) {
    throw new IndexOutOfBoundsException("null");
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题 ?

  1. 分析StackTrace
  2. 根据nullity,length或valid索引验证输入字符串
  3. 使用调试或日志
  4. 使用Generic Exception catch块

1.)分析StackTrace

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

例如 StringIndexOutOfBoundsException,然后寻找你package name indicating your class file然后去那条线并记住原因,只需应用解决方案

如果您在文档中研究异常及其原因,那么这是一个良好的开端.

2.)根据nullity,length或valid索引验证输入字符串

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

3.)使用调试或日志

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

日志就像检查点一样,所以当你的控件跨越这一点时,它们会产生细节,基本上它们是由枯萎系统给出的信息性消息,或者用户也可以使用Logs或Println消息放置日志消息

4.)使用Generic Exception catch块

Try-catch块总是有用处理,RuntimeExceptions因此您可以使用多个catch块来处理可能的问题并提供适当的详细信息

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 ");
}
Run Code Online (Sandbox Code Playgroud)

进一步的参考

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