我正在制作一个应用程序,它从网络获取一些数据作为 JSON,然后它应该显示在列表视图中。
到目前为止,我有一个类可以获取数据并按预期成功运行,然后我有一个自定义 ArrayAdapter 类。当我在各个地方使用 soem Log.d() 运行我的代码以检查代码是否正常工作时,应用程序将打开,下载 JSON,然后将其发送回我的活动,然后将数据发送到数组适配器成功
(通过调用发送到适配器的数据中第一个 JSONObject 的字段来测试它)。
据我所知,问题在于 getView() 方法没有被调用。
代码:
try {
listAdapter = new CropListAdapter(this, R.layout.crop_listitem,
crops.getJSONArray("crops"));
listView.setAdapter(listAdapter);
// setUpViews();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
适配器:
public class CropListAdapter extends ArrayAdapter<JSONArray> {
Context context;
JSONArray data;
int layoutResourceId;
CropHolder cropHolder;
public CropListAdapter(Context context, int layoutResourceId, JSONArray data) {
super(context, layoutResourceId);
// TODO Auto-generated constructor stub
this.context = context;
this.data = data;
this.layoutResourceId = layoutResourceId;
this.cropHolder = null;
}
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
Log.d("Working", "works here 38");
View row = convertView;
JSONObject crop;
try {
Log.d("Pos", Integer.toString(pos));
crop = (JSONObject) data.getJSONObject(pos);
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
cropHolder = new CropHolder();
cropHolder.tvCropId = (TextView) row
.findViewById(R.id.tvCropId);
cropHolder.tvCropName = (TextView) row
.findViewById(R.id.tvCropName);
cropHolder.ivCropImage = (ImageView) row
.findViewById(R.id.ivCropImage);
row.setTag(cropHolder);
} else {
cropHolder = (CropHolder) row.getTag();
}
cropHolder.tvCropId.setText(crop.getString("crop_id"));
cropHolder.tvCropName.setText(crop.getString("name"));
Log.d("Item", "creating item " + crop.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
static class CropHolder {
TextView tvCropName;
ImageView ivCropImage;
TextView tvCropId;
}
}