运行我的应用程序时出现NullPointerException:
logcat的
java.lang.NullPointerException:尝试在org.example.km.json3.Helper.SwipeListAdapter.getView上的空对象引用上调用虚拟方法'android.view.View android.view.View.findViewById(int)' (SwipeListAdapter.java:52)
课程如下:
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater layoutInflater;
private List<StockDetails> listStockDetails;
public SwipeListAdapter(Activity activity, List<StockDetails> listStockDetails) {
this.activity = activity;
this.listStockDetails = listStockDetails;
}
@Override
public int getCount(){
return listStockDetails.size();
}
@Override
public Object getItem(int position) {
return listStockDetails.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(layoutInflater == null) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView == null){
layoutInflater.inflate(R.layout.list_row, null);
}
//This is the line number : 52
TextView txtStockId = (TextView) convertView.findViewById(R.id.txtStockId);
TextView txtStockTag = (TextView) convertView.findViewById(R.id.txtStockTag);
TextView txtStockExchange = (TextView) convertView.findViewById(R.id.txtStockExchange);
TextView txtStockRate = (TextView) convertView.findViewById(R.id.txtStockRate);
TextView txtStockChange = (TextView) convertView.findViewById(R.id.txtStockChange);
TextView txtStockChangePercent = (TextView) convertView.findViewById(R.id.txtStockChangePercent);
TextView txtStockPreviousClosing = (TextView) convertView.findViewById(R.id.txtStockPreviousClosing);
txtStockId.setText(listStockDetails.get(position).id);
txtStockTag.setText(listStockDetails.get(position).t);
txtStockExchange.setText(listStockDetails.get(position).e);
txtStockRate.setText(listStockDetails.get(position).l);
txtStockChange.setText(listStockDetails.get(position).c);
txtStockChangePercent.setText(listStockDetails.get(position).cp);
txtStockPreviousClosing.setText(listStockDetails.get(position).pcls_fix);
return convertView;
}
}
答案 0 :(得分:1)
更改
if(convertView == null){
layoutInflater.inflate(R.layout.list_row, null);
}
要
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.list_row, null);
}
由于Views
是在第一次调用getView()
时创建的(尚未重用View
),因此convertView
为空。
您正在为这种情况正确地扩充布局......但是,您没有保存返回的View
。这样,convertView
保持为空,convertView.findViewById()
产生空指针异常
答案 1 :(得分:1)
你永远不会设置应该用inflater初始化的内容:
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.list_row, null);
}
这意味着convertView从未使用该布局初始化