7

I'm trying to get text copied into the clipboard using the following listener:

import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import com.orhanobut.logger.Logger;

public class ClipboardListener implements OnPrimaryClipChangedListener
{

    public void onPrimaryClipChanged()
    {
        // do something useful here with the clipboard
        // use getText() method
        Logger.d("Clipped");
    }
}

The listener is initialized as follows:

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener());

After the text is copied into the clipboard onPrimaryClipChanged is fired, but I don't know how to get the copied text in this method using ClipboardManager.getPrimaryClip() because the method is not available from the context and is not passed in the param of onPrimaryClipChanged.

Bennett McElwee
  • 24,740
  • 6
  • 54
  • 63
redrom
  • 11,502
  • 31
  • 157
  • 264

1 Answers1

9

I would suggest adding the listener as follows instead of creating a new class. I have included how to get text from the ClipData.

You mention being unable to access your context in the listener, I've added a comment within the code below showing how to do so.

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {

    @Override
    public void onPrimaryClipChanged() {
        ClipData clipData = clipBoard.getPrimaryClip();
        ClipData.Item item = clipData.getItemAt(0);
        String text = item.getText().toString();

        // Access your context here using YourActivityName.this
    }
});
Karen Forde
  • 1,117
  • 8
  • 20
  • It throws null pointer exception: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference – redrom Jul 06 '16 at 12:24
  • You'll probably have to add a safety check for item.getText() being null incase there is no text in the ClipBoard when onPrimaryClipChanged is fired. – Karen Forde Jul 06 '16 at 12:32
  • Is there any way to get this kind ClipBoard data in iOS ?? @KarenForde – Tapan Kumar Patro Mar 21 '17 at 12:51
  • @TapanKumarPatro I don't know sorry, I'm not an iOS developer – Karen Forde Apr 01 '17 at 15:35