android studio尝试在空对象引用上调用虚拟方法'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)'

时间:2019-03-27 11:57:02

标签: java android

当我尝试运行代码时,它给我一个错误,表明我正在尝试对空对象引用执行RecyclerView。 android studio检测到的问题在此行recyclerView.setHasFixedSize(true);中。有人知道问题吗?

这里是活动:

public class SalesHistoryActivity extends AppCompatActivity {

    @BindView(R.id.sales_recycler)
    RecyclerView recyclerView;

    SalesAdapter adapter;
    List<Sales> salesList;
    Sales sales;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sales_history);


        salesList = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SalesAdapter(this, salesList);
        recyclerView.setAdapter(adapter);

        loadItem();

    }

这是适配器

public class SalesAdapter extends RecyclerView.Adapter<SalesAdapter.ItemViewHolder> {

    private Context mCtx;
    private List<Sales> salesList;

    public SalesAdapter(Context mCtx, List<Sales> salesList){
        this.mCtx = mCtx;
        this.salesList = salesList;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View rootView = LayoutInflater.from(mCtx).inflate(R.layout.list_sales, null, false);
         RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        rootView.setLayoutParams(layoutParams);
        return new ItemViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {

        final Sales sales =salesList.get(position);

        holder.tvDate.setText(sales.getDate());
        holder.tvType.setText(sales.getType());
        holder.tvQty.setText(sales.getQty());
        holder.tvPrice.setText(mCtx.getString(R.string.price, sales.getPrice()));

    }

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

    public class ItemViewHolder extends RecyclerView.ViewHolder {

        TextView tvDate, tvType, tvQty, tvPrice;
        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这仅仅是因为您在使用ButterKnife库时忘记了绑定视图。因此,您需要通过添加ButterKnife.bind(this)来更改代码:

public class SalesHistoryActivity extends AppCompatActivity {

    @BindView(R.id.sales_recycler)
    RecyclerView recyclerView;

    ..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sales_history);

        ButterKnife.bind(this);

        // now your views are binded. You can access them

        ...

        recyclerView.setHasFixedSize(true);

        ...

    }

}