android.view.View android.view.View.findViewById(int)

时间:2019-01-28 09:40:12

标签: android

我的CustomAdapter有问题。该程序在Android Studio上运行良好,直到遇到障碍:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ android.view.View android.view.View.findViewById(int)”

我的代码:

public class CustomAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private ArrayList<ModuleModel> Items;

    TextView name, module, dueday, id;

    public CustomAdapter(Activity activity, ArrayList<ModuleModel> Items)
    {
        this.activity = activity;
        this.Items = Items;
    }
    @Override
    public int getCount() {
            return Items.size();
    }

    @Override
    public Object getItem(int i) {
        return Items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        if(inflater == null)
        {
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
        }
        id = convertView.findViewById(R.id.tvID);
        name = convertView.findViewById(R.id.tvRowName);
        module = convertView.findViewById(R.id.tvRowModule);
        dueday = convertView.findViewById(R.id.tvInforDueDay);

        ModuleModel mm = Items.get(position);
        id.setText(mm.getID());
        name.setText(mm.getName());
        module.setText(mm.getModule());
        dueday.setText(mm.getDueday());

        return convertView;
    }
}

3 个答案:

答案 0 :(得分:1)

您可以更改并尝试一次吗?

在您的代码中, convertView 始终为空,因为它向您抛出了NLE

if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
}

if(convertView == null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
}

答案 1 :(得分:0)

  

尝试一下

    id.setText(""+mm.getID());

答案 2 :(得分:0)

您的问题就在这里

if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
        }

如果您没有为convertView分配新值,则它为null,因此在到达以下代码块时会引发错误。