本文介绍了RecyclerView NullPointerException getItemCount中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请对此进行调查,并让我知道发生了什么问题.
Please look into this and let me know what went wrong.
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.但我收到此错误.
Null pointer exception at return itemsData.length; i need to design a listview inside a pager or inside a sliding tablayout. but im getting this error.
推荐答案
您传递给MyAdapter
的构造函数的itemsData
参数为空,或者您使用的第二个构造函数未初始化itemsData
类成员.您可以将其检查为null并从getItemCount
方法返回0:
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;
}
这篇关于RecyclerView NullPointerException getItemCount中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!