【发布时间】:2017-02-21 17:03:45
【问题描述】:
这是我的代码:
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 文档中给出的默认值。我只更改了网址。
这是我的错误信息:
java.lang.StringIndexOutOfBoundsException: 长度=28;区域开始=1; 区域长度=499 在 java.lang.String.substring(String.java:1931) 在 com.example.my.app.MainActivity$2.onResponse(MainActivity.java:50) 在 com.example.my.app.MainActivity$2.onResponse(MainActivity.java:46) 在 com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) 在 com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) 在 com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) 在 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) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
在调试过程中,我看到mTextView.setText("Response is: "+ response.substring(0,500)); 我的消息已发送给我,但文本视图从未更新,应用程序崩溃。
具体来说,它在 Looper.Java 文件中崩溃:
finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
traceTag 为 0。
我读到一些字符串边界是错误的,但我不知道如何修复它。
【问题讨论】:
-
阅读 StringIndexOutOfBoundsException 的文档。然后阅读您收到的错误信息。
-
虽然此异常与
ArrayIndexOutOfBoundsException的异常有关,但它不是重复的。例外情况不同。原因是不同的(尽管类似)。最重要的是,这个问题及其答案没有提及这个例外。