1

I was trying to add onClickListener to a button inside a RecyclerView that wii copy a string but it says getSystemService(CLIPBOARD_SERVICE) is not available.

public void onBindViewHolder(ViewHolder holder, int position) {
        holder.title.setText(cardItems.get(position).title);
        holder.content.setText(cardItems.get(position).content);
        holder.copyButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){

                myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                String text;
                text = EditText.getText().toString();
                myClip = ClipData.newPlainText("text", text);
                myClipboard.setPrimaryClip(myClip);

                Toast.makeText(getApplicationContext(), "Text Copied", Toast.LENGTH_SHORT).show();
            }
        });
    }
azizbekian
  • 60,783
  • 13
  • 169
  • 249
Dinesh Neupane
  • 382
  • 10
  • 19

4 Answers4

5

You need a Context in order to do that. Perform:

...
public void onClick(View v) {
    myClipboard = (ClipboardManager) v.getContext().getSystemService(CLIPBOARD_SERVICE);
    ...
}
azizbekian
  • 60,783
  • 13
  • 169
  • 249
2

Adapter don't have its own existence.its work for activity. so if you want to call that type service or other activity things you have to pass context of that activity which is using this adapter. so make call with context

Like

 myClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
Ghanshyam Sharma
  • 451
  • 9
  • 21
0

You have to use a context to get a System Service, add it in your constructor and pass it as a parameter when you create your adapter:

private Context context;

//Constructor 
public YourAdapter(Context context){
this.context = context;
}

public void onBindViewHolder(ViewHolder holder, int position) {
        holder.title.setText(cardItems.get(position).title);
        holder.content.setText(cardItems.get(position).content);
        holder.copyButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){

                myClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
                String text;
                text = EditText.getText().toString();
                myClip = ClipData.newPlainText("text", text);
                myClipboard.setPrimaryClip(myClip);

                Toast.makeText(getApplicationContext(), "Text Copied", Toast.LENGTH_SHORT).show();
            }
        });
    }
Luiz Fernando Salvaterra
  • 4,192
  • 2
  • 24
  • 42
0

try this one

In Adapter class : add this constructor

private Activity mActivity;

    public adapter(Activity activity){
         mActivity = activity;
}

then call the getSystemService() by this mActivity variable

myClipboard =(ClipboardManager)mActivity.getSystemService(CLIPBOARD_SERVICE);
user1517638
  • 972
  • 1
  • 10
  • 16