我创建了一个在片段中带有回收器视图的应用程序,但由于保持器.titleText.setText(itemArrayList.get(position).getText())中的以下异常,我的应用程序每次运行时都会崩溃:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
下面是MyAdapter代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
Context context;
ArrayList<Item> itemArrayList;
public MyAdapter(Context context, ArrayList<Item> itemArrayList) {
this.context = context;
this.itemArrayList = itemArrayList;
}
@NonNull
@Override
public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.fragment_item_list, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Item item = itemArrayList.get(position);
holder.titleText.setText(itemArrayList.get(position).getText());
holder.titleImage.setImageResource(item.getImage());
}
@Override
public int getItemCount() {
return itemArrayList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
ImageView titleImage;
TextView titleText;
public ViewHolder(@NonNull View itemView) {
super(itemView);
titleImage = itemView.findViewById(R.id.titleiImage);
titleText = itemView.findViewById(R.id.titleText);
}
}
}
下面是我的ItemFragment代码:
public class ItemFragment extends Fragment {
private ArrayList<Item> itemArrayList;
private int[] imageResourceId;
private String[] texts;
private MyAdapter myAdapter;
private RecyclerView recyclerView;
public ItemFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
dataInitialize();
myAdapter = new MyAdapter(getContext(), itemArrayList);
recyclerView = (RecyclerView) view;
recyclerView.setAdapter(myAdapter);
return view;
}
private void dataInitialize() {
itemArrayList = new ArrayList<>();
imageResourceId = new int[] {
R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background,
R.drawable.ic_launcher_background,
};
texts = new String[] {
getString(R.string.blackpink),
getString(R.string.redvelvet),
getString(R.string.itzy),
};
for(int i = 0; i < texts.length; i++) {
Item item = new Item(imageResourceId[i], texts[i]);
itemArrayList.add(item);
}
}
}
我搜索了网页,但仍然无法找到解决方案。我将感谢您的帮助^^
1条答案
按热度按时间vxqlmq5t1#
在您适配器中,似乎您在“R.layout.fragment_item_list”中放置了错误的布局:
如果不是,请确保在'R.layout.fragment_item_list'中有一个id为'titleText'的Textview