BXUMZSE BXUMZSE - 29 days ago 16
Android Question

Error loading image url with Glide

What I'm trying to do is to display images using an image url and I'm using the glide library to load these images however whenever I try to run the application, the images are unable to show or wont load on the activity. I'm able to see the text being displayed but not the images

This is the Error I'm getting

java.lang.IllegalArgumentException: You cannot start a load on a null Context
11-11 03:23:01.713 5428-5428/? W/System.err: at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:84)
11-11 03:23:01.713 5428-5428/? W/System.err: at com.bumptech.glide.Glide.with(Glide.java:629)


This is the code

public class SampleAdapter extends RecyclerView.Adapter <SampleAdapter.ViewHolder> {

private List<SampleModel> list;
private Context mContext = null;

public SampleAdapter(List<SampleModel> sampleModelList) {
this.list = sampleModelList;
}

@Override
public SampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_item, parent, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(WatchlistAdapter.ViewHolder holder, int position) {

String image = "https://image.tmdb.org/t/p/w500/9HE9xiNMEFJnCzndlkWD7oPfAOx.jpg";

try{
final SampleModel sample = list.get(holder.getAdapterPosition());

if(sample != null) {
holder.title.setText(sample.getTitle());
Glide.with(mContext).load(image)
.placeholder(R.drawable.placeholder)
.dontAnimate()
.fitCenter()
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.cover);
} else {
Glide.clear(holder.cover);
}
} catch(Exception e) {
e.printStackTrace();
}
}

@Override
public int getItemCount() {
return (list != null? list.size():0);
}

public class ViewHolder extends RecyclerView.ViewHolder {

public TextView title;
public ImageView cover;

public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
cover= (ImageView) itemView.findViewById(R.id.coverImage);
}
}

Answer

do this :

public SampleAdapter(List<SampleModel> sampleModelList, Context context) {
    this.list = sampleModelList;
    mContext = context ;
}