CustomArrayAdapter android nullpointerexception

时间:2015-02-01 18:23:09

标签: java android android-listview nullpointerexception android-arrayadapter

有谁能告诉我为什么我在构造函数中遇到超级方法的nullpointerexception?

它总是在super中面对空指针异常,但context和historyItems不为null。

public class HistoryItemAdapter extends ArrayAdapter<HistoryItem> {

    Context context;
    HistoryItem[] historyItems=null;

    public HistoryItemAdapter(Context context, HistoryItem[] historyItems) {
        super(context,R.layout.list_history_single,historyItems); //Exception Here
        this.context = context;
        this.historyItems = historyItems;
    }

    private class ViewHolder {
        TextView historyName;
        TextView historyTitle;
        ImageView historyImage;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(convertView==null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            convertView = inflater.inflate(R.layout.list_history_single,null);
            viewHolder.historyName = (TextView) convertView.findViewById(R.id.history_name);
            viewHolder.historyTitle = (TextView) convertView.findViewById(R.id.history_title);
            viewHolder.historyImage = (ImageView) convertView.findViewById(R.id.history_image);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        HistoryItem historyItem = historyItems[position];

        viewHolder.historyImage.setImageBitmap(historyItem.bitmap);
        viewHolder.historyName.setText(historyItem.name);
        viewHolder.historyTitle.setText(historyItem.title);

        return convertView;
    }
}

2 个答案:

答案 0 :(得分:0)

您在适配器中传递的值为null,因为

  1. 您尚未初始化它。
  2. 初始化在后台操作中完成,后台操作在listview中分配适配器后调用。
  3. 像这样初始化你的变量

    HistoryItem[] historyItem = new HistoryItem[size];
    

    当您完成下载数据调用时

    adapter.notifyDataSetChanged();
    

    但似乎你在开始下载之前不知道它的大小。在这种情况下,您可以移动此代码

    adapter = new HistoryItemAdapter(context,historyItem);
    listView = (ListView) reportHistory.findViewById(R.id.list_history);
    listView.setAdapter(adapter);
    

    在您的方法done()内,这是您的后台任务的回调。

答案 1 :(得分:0)

您的构造函数中有2个参数,但您的super有3个参数。