我正在使用Parse.com服务器,我正在尝试从服务器获取数据并将其放入具有4个TextView字段的自定义列表中。我收到的数据很好,但我在列表的第一个位置的适配器中有问题我在所有textView字段上得到空指针异常。在其他领域没有问题。
这是我正在使用的代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coupon_list);
init();
}
private void init(){
couponListView = (ListView)findViewById(android.R.id.list);
couponList = new ArrayList<ParseObject>();
query = new ParseQuery(COUPON_CLASS_NAME);
couponListView.setOnItemClickListener(this);
query.findInBackground(new FindCallback() {
@Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) { //objects retrieved well
couponList.addAll(list);
}
else {
toaster("problem find coupons");
}
MyAdapter adapter = new MyAdapter(
getApplicationContext(),
android.R.layout.simple_list_item_1,
R.id.tv_coupoun_content,
couponList);
setListAdapter(adapter);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_coupon_list, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
public class MyAdapter extends ArrayAdapter<ParseObject> {
public MyAdapter(Context context, int resource, int textViewResourceId, ArrayList<ParseObject> couponList) {
super(context, resource, textViewResourceId, couponList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater lf = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = lf.inflate(R.layout.coupon_row, parent, false);
tvCouponContent = (TextView)findViewById(R.id.tv_coupoun_content);
tvBusinessName = (TextView)findViewById(R.id.tv_business_name);
tvBusinessStreet = (TextView)findViewById(R.id.tv_street);
tvBusinessCity = (TextView)findViewById(R.id.tv_city);
//in position 0 the log below is true for all in the rest its false
Log.d("Shalom","shalom - " + Boolean.toString(tvCouponContent == null)+" "+
Boolean.toString(tvBusinessName == null)+" "+
Boolean.toString(tvBusinessStreet == null)+" "+
Boolean.toString(tvBusinessCity == null)+" "+
Integer.toString(position));
/*tvCouponContent.setText(coupons.getString(COUPON_CONTENT));
tvBusinessName.setText(coupons.getString(COUPON_BUSINESS_NAME));
tvBusinessStreet.setText(coupons.getString(COUPON_STREET));
tvBusinessCity.setText(coupons.getString(COUPON_CITY));*/
return row;
}
}
答案 0 :(得分:2)
您的Adapter构造函数错误,请使用以下构造函数:
public MyAdapter(Context context, ArrayList<ParseObject> couponList) {
super(context, R.layout.coupon_row, couponList);
}
实例化它:
MyAdapter adapter = new MyAdapter(getApplicationContext(),couponList);
要将项目膨胀到列表视图中,您必须使用膨胀的对象:
View row = lf.inflate(R.layout.coupon_row, parent, false);
tvCouponContent = (TextView)findViewById(R.id.tv_coupoun_content); //BAD
tvCouponContent = (TextView)row.findViewById(R.id.tv_coupoun_content);//GOOD
您应该使用View Holder模式:http://www.jmanzano.es/blog/?p=166