serkan stack serkan stack - 1 month ago 7
Android Question

java.lang.IllegalArgumentException: Context must not be null

I am using adapter to show images. In Adapter, How to get context when using Picasso?
I tried different solutions but I couldn't solve. What should I do when using picasso in Adapter? Context is a big problem for developers I see on the internet.

package gc.x;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import gc.ovidos_challenge.R;
import gc.ovidos_challenge.models.Image;

import java.net.URL;
import java.util.List;


public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.MyViewHolder> {

private List<Image> imagesList;

private Context context;

public ImagesAdapter(Context context) {
this.context = context;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView imageview;

public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.textview);
imageview = (ImageView) view.findViewById(R.id.imageurl);

}
}


public ImagesAdapter(List<Image> imagesList) {
this.imagesList = imagesList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_image, parent, false);

return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = imagesList.get(position);
holder.title.setText(image.title);
Picasso.with(this.context).load(image.url).into(holder.imageview);


// holder.imageview.setImageBitmap(image.getBitmapFromURL());

}

@Override
public int getItemCount() {
return imagesList.size();
}


}

Answer

you have created two constructors one for context and one for your data. use one constructor to initialize both of them

like this

public ImagesAdapter(Context context,List<Image> imagesList) {
        this.context = context;
this.imagesList=imagesList;
    }