android-getItemCount中的RecyclerView NullPointerException问题
作者:互联网
请调查一下,让我知道出了什么问题.
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;的空指针异常;我需要在一个寻呼机或一个滑动的布局中设计一个listview.但我收到此错误.
解决方法:
传递给MyAdapter的构造函数的itemsData参数为null,或者您使用的第二个构造函数未初始化itemsData类成员.您可以检查它是否为null并从getItemCount方法返回0:
@Override
public int getItemCount() {
return itemsData == null ? 0 : itemsData.length;
}
标签:recycler-adapter,android,android-recyclerview 来源: https://codeday.me/bug/20191011/1890780.html