我正在尝试通过从外部 url 获取数据来构建 ListView(位于 Fragment 内)。
我正在使用 Volley 来执行此请求,但是当我尝试运行该应用程序时,它什么也没显示。
这是片段代码:
public class DashboardFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dashboard, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final List<NewsFeed> newsFeed = new ArrayList<>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "http://webservice_url/", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("data");
NewsFeed feed = new NewsFeed(obj.getString("title"), obj.getString("description"), obj.getString("date"));
newsFeed.add(feed);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
ListView listView = (ListView) getActivity().findViewById(R.id.newsFeed);
NewsFeedAdapter adapter = new NewsFeedAdapter(getActivity(), (ArrayList<NewsFeed>) newsFeed);
listView.setAdapter(adapter);
}
}
这是 NewsFeed 类和适配器:
public class NewsFeed {
public String title;
public String description;
public String date;
public NewsFeed(String title, String description, String date) {
this.title = title;
this.description = description;
this.date = date;
}
}
public class NewsFeedAdapter extends ArrayAdapter<NewsFeed> {
// View lookup cache
private class ViewHolder {
TextView title;
TextView description;
TextView date;
}
public NewsFeedAdapter(Context context, ArrayList<NewsFeed> newsFeedArrayList) {
super(context, R.layout.fragment_dashboard_news, newsFeedArrayList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
NewsFeed newsFeed = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.fragment_dashboard_news, parent, false);
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.description = (TextView) convertView.findViewById(R.id.description);
viewHolder.date = (TextView) convertView.findViewById(R.id.date);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(newsFeed.title);
viewHolder.description.setText(newsFeed.description);
viewHolder.date.setText(newsFeed.date);
return convertView;
}
}
此外,当我在没有 Volley 请求的情况下添加元素时,它正在工作。