java.lang.IllegalArgumentException:Context不能为null

时间:2016-10-24 16:10:37

标签: java android picasso android-context

我正在使用适配器来显示图像。在Adapter中,如何在使用Picasso时获取上下文? 我尝试了不同的解决方案,但我无法解决。在适配器中使用picasso时我该怎么办?对于我在互联网上看到的开发人员而言,上下文是一个大问题。

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();
    }


}

1 个答案:

答案 0 :(得分:1)

您已创建了两个构造函数,一个用于上下文,另一个用于数据。使用一个构造函数来初始化它们

像这样

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