请仔细研究一下,让我知道出了什么问题。
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ItemData[] itemsData;
public MyAdapter(ItemData[] itemsData) {
this.itemsData = itemsData;
}
public MyAdapter(String[] titles, int[] icons, String name, String email, int profile) {}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab1list, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.txtViewTitle.setText(itemsData[position].getTitle());
viewHolder.imgViewIcon.setImageResource(itemsData[position].getImageUrl());
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.abb);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.baa);
}
}
// Return the size of your itemsData (invoked by the layout manager)
@Override
public int getItemCount() {
return itemsData.length;// here im getting the `null` pointer exception error
}
}
返回itemsData.length时出现空指针异常;我需要在寻呼机内或滑动tablayout内设计一个列表视图。但我得到了这个错误。
答案 0 :(得分:5)
Your itemsData
parameter passed to the MyAdapter
's constructor is null or you are using the second constructor which is not initializes the itemsData
class member. You can check it for null and return 0 from the getItemCount
method:
@Override
public int getItemCount() {
return itemsData == null ? 0 : itemsData.length;
}