Emiliano Rodriguez Emiliano Rodriguez - 4 months ago 5x
Java Question

Filling an array with a JSON, but losing the information after exiting the method

Im trying to create a list here, but the issue is that after i fill the array daysList with information, everything is lost after i exit onResponse.

If i set the textview inside the onResponse method it works, but it does not if i do it outside (like in this case), i get null pointer exception.

I understand that i have to define the array as static to keep the data, but it's not working either! How do i fix this?

public class MainFragment extends Fragment {

private View view;
private RequestQueue requestQueue;
private WeatherAdapter weatherAdapter;
public static WeatherForecast weatherForecast;
public static WeatherForecast.List[] daysList;

private ListView listView;
private TextView textView;

String URL = "requestURL";

public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.main_fragment,null);

textView = (TextView) view.findViewById(R.id.textview);

requestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonWeatherRequest = new JsonObjectRequest(
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
weatherForecast = parseWeatherToJson(response.toString());
daysList = weatherForecast.getList();
//textView.setText("Humidity is: " + daysList[0].getHumidity()); <--- If i set it here it works!
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "On Error!");


textView.setText("Humidity is: " + daysList[0].getHumidity()); // <---- This throws nullpointer.


jsonWeatherRequest is a async request which hits the server and gets the response in onResponse() callback. When you are setting the TextView with the list value outside onResponse(), at that moment your request is not completed and thus your list is null.

So if you want to access the list, then you have to do that in onResponse() callback.