I'm new to android dev and I wanted to make app with fragments and use RecyclerView inside it. I'm getting error which is saying that I'm trying to use setText on a null object. My code looks like that :
public static class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
private static String[] newsTitle = new String[] {...};
private static String[] newsDescs = new String[] {...};
public ContentAdapter(ViewGroup parent) {}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView titles;
TextView descs;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_list, parent, false));
titles = (TextView) parent.findViewById(R.id.list_title);
descs = (TextView) parent.findViewById(R.id.list_desc);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.titles.setText(newsTitle[position]); //Here is error
holder.descs.setText(newsDescs[position]);
}
@Override
public int getItemCount() { return newsTitle.length; }
}
Here is a correct example if a view holder
public static class HeaderVH extends RecyclerView.ViewHolder {
public TextView textView;
public HeaderVH(View view){
super(view);
textView = (TextView)view;
}
}
You need to pass in a the View object of the row to the viewholder, not the parent View object. This is an example of onCreateViewHolder()
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_setting_header, parent, false);
RecyclerView.ViewHolder vh = new HeaderVH(v);
return vh;
}
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html
https://www.bignerdranch.com/blog/recyclerview-part-1-fundamentals-for-listview-experts/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.