片段'onCreateView()

时间:2016-08-25 14:31:09

标签: java android android-studio android-fragments android-volley

我正在尝试使用volley从URL获取一些国家/地区数据。 在 onResponse()数据成功添加到 countryList countryList.size()表示它有5个国家/地区。 但是在 onCreateView()中,当我尝试使用 countryList 时,由于 countryList.size(),它为null并抛出 NullPointerException countryList 具有空值。 在此先感谢,这是代码:

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);

    }
}

2 个答案:

答案 0 :(得分:1)

您尚未初始化ArrayList&lt; Countries&gt; countryList。在将RequestCountries()方法作为

调用之前,尝试在onCreateView中初始化ArrayList

countryList = new ArrayList&lt;&gt;();

答案 1 :(得分:0)

你知道Volley执行Asynchronously意味着方法后凌空代码可以执行它不等待执行凌空代码并且响应是recive.in你的情况它发生了,你的toast es在凌空代码完成执行之前执行。所以你需要把你的所有代码放在urler volley response.try中的方法RequestCountries()之后