A.Fitzgerald
A.Fitzgerald

Reputation: 51

Trouble adding functionality to the activity from the adapter

I am trying to add an on click listener to an image holder that is created in the adapter class and the tutorial I am following using the .this keyword but I need to refer to the activity in the adapter class? I will attach a screenshot to make it clearer

Toast.makeText(JudgeActivity.this, post_key, Toast.LENGTH_LONG).show();

This is the line causing the error, (JudgeActivity.this is not an enclosing class)

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UploadClass> mUploads;



public ImageAdapter(Context context, List<UploadClass> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public  ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {

    final String post_key = mUploads.get(position).toString();
    UploadClass uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);

    holder.imageView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Toast.makeText(JudgeActivity.this, post_key, Toast.LENGTH_LONG).show();
        }
    });

}

ScreenShot of Code

Upvotes: 1

Views: 53

Answers (1)

Martinez
Martinez

Reputation: 149

You need to provide Context instance. I can see your adapter will have this instance when it's constructed. When you call new ImageAdapter(Context context, List<UploadClass> uploads) from your activity or fragment, you pass your Context object (which in this case is your Activiy) to the ImageAdapter instance so you can use it in your methods.

So correct replacement would be:

Toast.makeText(mContext, post_key, Toast.LENGTH_LONG).show();

P.S. Your code will still work if the adapter was inner class of JudgeActivity. Referring to JudgeActivity.this context should have been successful if you didn't separated ImageAdapter class from JudgeActivity class.

Upvotes: 1

Related Questions