如何从http凌空的OnResponse创建一个setText

时间:2018-06-16 10:39:33

标签: java android android-volley

我尝试更改主要活动上声明的textview,但我遇到错误:java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.setText(String)' on a null object reference

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

...

// Instantiate the RequestQueue.
Context context = ActivityMain.getContext()
RequestQueue queue = Volley.newRequestQueue(context);
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);

我认为这是线程的问题,因为OnResponse是在后台线程上调用的,而且setText()必须在UiThread上完成。但我现在不知道如何解决它......

我试过了:

runOnUiThread(new Runnable(){
        public void run() {
            // update UI
        }

但它也不起作用..

0 个答案:

没有答案