I am trying to create a recycleView with image and toolbar. this is my adapter
public class ImageAdabter extends RecyclerView.Adapter<ImageViewHolder> {
private Context mContext;
private List<Integer> listImages;
public ImageAdabter(Context mContext) {
this.mContext = mContext;
this.listImages=getImages();
}
private List<Integer> getImages() {
List<Integer> results = new ArrayList<>();
results.add(R.drawable.ballon);
results.add(R.drawable.owl);
results.add(R.drawable.fish);
return results;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_images,parent,false);
return new ImageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ImageViewHolder holder, int position){holder.imageView.setImageResource(listImages.get(position));
}
@Override
public int getItemCount() {
return listImages.size();
}
and i create a ImageViewHolder class . this is may code
public class ImageViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ImageViewHolder(@NonNull View itemView) {
super(itemView);
itemView= itemView.findViewById(R.id.image_outline);
}
My main class code is
initTollbar();
initView();
}
private void initView() {
recyclerView = findViewById(R.id.recycle_view_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adabter = new ImageAdabter(this);
recyclerView.setAdapter(adabter);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initTollbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
int toolbar_item_color= ResourcesCompat.getColor(getResources(),R.color.blue,null);
toolbar.setTitleTextColor(toolbar_item_color);
toolbar.setSubtitleTextColor(toolbar_item_color);
getSupportActionBar().setTitle("Mes Images");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.close);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
when i run my code i got this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference .adabters.ImageAdabter.onBindViewHolder(ImageAdabter.java:44) .adabters.ImageAdabter.onBindViewHolder(ImageAdabter.java:17)
thanks
CodePudding user response:
Use below code
public class ImageViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ImageViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_outline);
}