Can't save the value of Volley's answer for later use, it becomes null
I was just experimenting with Volley to find out the network call. I found this rather odd, so I just want it to happen. Android developer guide was a similar example for Volley and I changed a bit so that the answer is held in line responseJSON
and I use to set it to textView in action. When I set the textView function inside onResponse()
, the result is displayed as text (commented line), but if I do it outside , then the function shown below is responseJSON
string turn null
(I checked through toast) and so the textView looks empty. Why is this happening? WhyresponseJSON
just doesn't bind to the response, the scope is still valid, so can't figure out why this is happening.
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);
}
}
source to share
In your method, onCreate
mTextView.setText(reponseJSON);
you are just setting the text to text representation, you are not setting a reference to the reponseJSON object,
And yours StringRequest
is an asynchronous request, the response will be a little later, as soon as you receive the response that you set to the object reponseJSON
. if you want to pop the value into the text view, you must set the text value again.
source to share