Unable to hold Volley response value for further use, it turns null

Viewed 84

I was just experimenting with Volley to learn network call. I found this rather strange so I just want to why this happens. The android developer guide had similar example for Volley and I changed a little bit so that the response is held in the string responseJSON and I use that to set it to a textView in the activity. When I set the textView within the onResponse() function, the result is displayed in the textview(commented line) but if I do it outside the function like shown below the responseJSON string turns null(I checked via toast) and so the textView appears blank. Why does this happen? Why doesn't responseJSON simply bind to response, scope is still valid so unable to understand why this happens.

package com.example.imnobody.sampleprojectnetwork;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

    private String reponseJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


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


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



        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        reponseJSON = response;
                        //mTextView.setText(reponseJSON);


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "nothing", Toast.LENGTH_SHORT).show();
            }
        });

        queue.add(stringRequest);

        mTextView.setText(reponseJSON);

    }
}
1 Answers
Related