java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.TableRow.addView(android.view.View)'

时间:2018-10-06 14:00:55

标签: java android android-recyclerview nullpointerexception android-tablelayout

我正在尝试将表布局与recyclerView一起使用,但出现错误:java.lang.NullPointerException:尝试在null上调用虚拟方法'void android.widget.TableRow.addView(android.view.View)'对象引用。

有我的适配器类:

public class CompanyAdapter extends RecyclerView.Adapter<CompanyAdapter.bookViewHolder> {

ArrayList<DataClass> arrayList;
TextView deposit;
TextView purchase;
TextView date;
TableRow tableRow;
TableLayout tableLayout;

public CompanyAdapter(ArrayList<DataClass> arrayList){
    this.arrayList = arrayList;
}

@Override
public bookViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    View view = 

 LayoutInflater.
from(context).inflate(R.layout.company_list_item,parent,false);
    return new bookViewHolder(view);
}

@Override
public void onBindViewHolder(bookViewHolder holder, int position) {
    DataClass dataClass = arrayList.get(position);
    holder.bind(dataClass);
    //bookNameTV.setText(dataClass.getBook());
    //authorNameTV.setText(dataClass.getAuthor());


}

@Override
public int getItemCount() {
    return arrayList.size();
}

public class bookViewHolder extends RecyclerView.ViewHolder{



    public bookViewHolder(View itemView) {
        super(itemView);
        deposit = (TextView) itemView.findViewById(R.id.deposit);
        purchase = (TextView) itemView.findViewById(R.id.purchase);
        date = (TextView) itemView.findViewById(R.id.date);
        tableLayout = (TableLayout) 
itemView.findViewById(R.id.maintablelayout);

    }

    public void bind(DataClass dataClass){
        deposit.setText(Integer.toString(dataClass.getAmount()));
        purchase.setText(Integer.toString(dataClass.getAmount()));
        date.setText(dataClass.date);
        tableRow.addView(deposit);
        tableRow.addView(purchase);
        tableRow.addView(date);
        tableLayout.addView(tableRow, new TableLayout.LayoutParams(
                TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));// giving error

    }
}
}

还有一个问题,是否有更好的方法在不使用任何库的情况下将tableLayout与recycler View一起使用?
谢谢..!

3 个答案:

答案 0 :(得分:0)

您没有在任何地方初始化tableRow

答案 1 :(得分:0)

您必须创建新的TableRow

使用此代码

AbcBase

答案 2 :(得分:0)

TableRow是一个实例变量,因此JAVA会在运行时使用null值对其进行初始化,并且您无法调用任何具有null值的方法。您必须将一个对象分配给TableRow参考变量。

喜欢:

tableRow=new TableRow(context);