我试图在此处创建列表,但问题是在我用信息填充数组daysList之后,退出onResponse后一切都丢失了。
如果我在onResponse方法中设置textview可以工作,但如果我在外部(例如在这种情况下)进行操作则不会,我会得到空指针异常。
我知道我必须将数组定义为静态数组以保留数据,但是它也不起作用!我该如何解决?
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(
URL,
null,
new Response.Listener<JSONObject>() {
@Override
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!
weatherAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "On Error!");
}
}
);
requestQueue.add(jsonWeatherRequest);
textView.setText("Humidity is: " + daysList[0].getHumidity()); // <---- This throws nullpointer.
}
最佳答案
jsonWeatherRequest
是一个异步请求,它会到达服务器并在onResponse()
回调中获取响应。当将列表值设置为TextView
以外的onResponse()
时,此时您的请求尚未完成,因此列表为空。
因此,如果要访问列表,则必须在onResponse()
回调中执行此操作。