IllegalArgumentException:Context不能为null。使用picaso& Recyclerview

时间:2016-09-22 17:50:36

标签: java android android-recyclerview

当我尝试使用recylerview和picaso加载图像时,收到此错误“IllegalArgumentException:Context不能为null。”

*我试图使用recylerview来显示我已经完成的一堆图像然后我尝试使用picaso加载图像加载。 *我也尝试使用“this”关键字,但这不起作用。

主要活动。

public class MainActivity extends AppCompatActivity {
//Dummydata or place holderdata.


final static int[] dummyImages={R.drawable.color_black,R.drawable.color_white,R.drawable.color_brown,R.drawable.color_dusty_yellow,R.drawable.color_mustard_yellow,R.drawable.color_red};
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);


    // use a linear layout manager
    mLayoutManager = new GridLayoutManager(getApplicationContext(),2);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // specify an adapter (see also next example)
    mAdapter = new RecycleAdapter(dummyImages);
    mRecyclerView.setAdapter(mAdapter);


}

}

我的Adpater

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

private String[] adumyDataSet;
private int[] adumyimage;
private Context context;


// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public static class ViewHolder extends RecyclerView.ViewHolder {
    // Your holder should contain a member variable
    // for any view that will be set as you render a row
    public ImageView colorImageView;

    // We also create a constructor that accepts the entire item row.
    // and does the view lookups to find each subview
    public ViewHolder(View itemView) {
        // Stores the itemView in a public final member variable that can be used
        // to access the context from any ViewHolder instance.
        super(itemView);
        colorImageView = (ImageView) itemView.findViewById(R.id.colorsBitch);

    }
}

public RecycleAdapter (int[] dummyDataSet){

    adumyimage=dummyDataSet;

}

@Override
public RecycleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view,parent,false);
    return new ViewHolder(v);
}

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

    Picasso.with(context).load(adumyimage[position]).into(holder.colorImageView);

}

@Override
public int getItemCount()
{
    return adumyimage.length;
}

}

1 个答案:

答案 0 :(得分:3)

使用此: 将上下文作为构造函数发送到适配器

public RecycleAdapter (int[] dummyDataSet,Context context){
  this.context=context;
  adumyimage=dummyDataSet;

}

在您的活动中

mAdapter = new RecycleAdapter(dummyImages,this);