newRequestQueue Android的Volley崩溃

时间:2016-09-24 11:41:27

标签: android android-volley

我想在对特定网址发出GET / POST请求时使用 Volley 来捕获服务器响应。

为此,我尝试使用the Android Developer page中的示例代码:

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

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

但是,当我在变量

中指定服务器的URL时,应用终止
String url ="http://www.google.com";

为什么会发生这种情况?

更新:这是logcat:

[ 09-24 07:49:55.360 26661:26661 D/]HostConnection::get() New Host Connection established 0xb7a6c690, tid 26661
09-24 07:49:55.410 26661-26661/test.com.test D/OpenGLRenderer: Enabling debug mode 0
09-24 07:49:55.480 26661-26661/test.com.test D/AndroidRuntime: Shutting down VM
09-24 07:49:55.480 26661-26661/test.com.test W/dalvikvm: threadid=1: thread     exiting with uncaught exception (group=0xb2cddb20)
09-24 07:49:55.490 26661-26661/test.com.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: test.com.test, PID: 26661
java.lang.StringIndexOutOfBoundsException: length=256; regionStart=0; regionLength=500
    at java.lang.String.startEndAndLength(String.java:588)
    at java.lang.String.substring(String.java:1475)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:39)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:35)
    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:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您必须在RequestQueue queue;之前声明onCreate(),然后在onCreate()中初始化