0
我正在使用Volley和GSON來解析遠程JSON。這裏是我的片段做的:無法將JSON填充到ListView
public class LatestFragment extends ListFragment implements OnScrollListener {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
arrItemList = new ArrayList<ItemListModel>();
va = new LatestAdapter(getActivity(), arrItemList);
lv = getListView();
setListAdapter(va);
lv.setOnScrollListener(this);
loadItemList(1);
}
private void loadItemList(int page) {
mRequestQueue = Volley.newRequestQueue(getActivity());
GsonRequest<LatestContainer> myReq = new GsonRequest<LatestContainer>(
Method.GET, url, LatestContainer.class,
createMyReqSuccessListener(), createMyReqErrorListener());
mRequestQueue.add(myReq);
}
private Response.Listener<LatestContainer> createMyReqSuccessListener() {
return new Response.Listener<LatestContainer>() {
@Override
public void onResponse(LatestContainer response) {
try {
for (int i = 0; i < response.getResults().size(); i++) {
ItemListModel ilm = new ItemListModel();
ilm.setCategory(response.getResults().get(i).getCategory());
ilm.setItem_id(response.getResults().get(i).getItem_id());
ilm.setName(response.getResults().get(i).getName());
ilm.setPrice(response.getResults().get(i).getPrice());
ilm.setUser_id(response.getResults().get(i).getUser_id());
arrItemList.add(ilm);
}
LatestAdapter
public class LatestAdapter extends BaseAdapter {
public LatestAdapter(Context context, ArrayList<ItemListModel> items) {
this.arrItemList = items;
this.context = context;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
lf = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
vh = new ViewHolder();
view = lf.inflate(R.layout.row_latest_listview, null);
vh.tvName = (TextView) view.findViewById(R.id.txtItemName);
vh.tvCategory = (TextView) view.findViewById(R.id.txtCategory);
vh.tvPrice = (TextView) view.findViewById(R.id.txtPrice);
vh.tvThumbnail = (ImageView) view.findViewById(R.id.imgPhoto);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
ItemListModel nm = arrItemList.get(i);
vh.tvCategory.setText(nm.getCategory());
vh.tvPrice.setText("RM " + nm.getPrice());
vh.tvName.setText(nm.getName());
return view;
}
然而,當我運行代碼,列表視圖似乎並沒有被填充。但解析是成功的。我可以在logcat中看到解析的字符串。所以反序列化在這裏不是問題。我現在做錯了什麼?
在你的適配器中必須(我可能是錯的)被重寫的其他函數,比如getCount(),給我們代碼。 – hypd09
還確保您的列表在將數據傳遞到適配器的構造函數之前已填充數據 – Raghunandan
發佈您的json和GSON映射類。 –