I am trying to get some country data from a URL using volley. In onResponse() data is successfully added to countryList and countryList.size() shows it has 5 countries. But in onCreateView(), when I try to use countryList, it is null and throws NullPointerException because of countryList.size() as countryList has null value. Thanks in advance, here's the code:
public class MyAddress extends Fragment {
ArrayList<Countries> countryList;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.shipping_address, container, false);
RequestCountries();
Toast.makeText(getContext(), countryList.size(), Toast.LENGTH_SHORT).show();
//Some code to use countryList
return rootView;
}
private void RequestCountries() {
final String urlLink = ConstantValues.BASE_URL + "getCountries";
StringRequest countryRequest = new StringRequest
(
Request.Method.GET,
urlLink,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject jsonResponse = new JSONObject(response);
JSONArray countries = jsonResponse.getJSONArray("countries");
for (int i=0; i< countries.length(); i++) {
JSONObject countryInfo = countries.getJSONObject(i);
String country_id = countryInfo.getString("country_id");
String country_name = countryInfo.getString("country_name");
Countries country = new Countries();
country.setCountry_id(country_id);
country.setCountry_name(country_name);
countryList.add(country);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(countryRequest);
}
}