Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getPrimaryClip() returns ClipData { text/plain {NULL} }

Please help me to solve this problem. This is my code

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

        clipboard.addPrimaryClipChangedListener(this);


        return START_STICKY;
    }

    @Override
    public void onPrimaryClipChanged() {

        Log.d("log",clipboard.getPrimaryClip()+"");

        ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

        String clipText = item.getText().toString();

        Log.d("log",clipText);

        new SendClipBoardData().execute(postClipDataUrl,clipText);
    }

Sometimes i'm getting error at ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

Error: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

The clipboard.getPrimaryClip() returns ClipData { text/plain {NULL} }, but when i paste the same copied text in my note, i can see the text, i can't detect the problem,sometimes it work sometimes not.

And one more question, when copy works fine, i'm getting copied text result two or three times,but my event is working one time, what it can be ? Thanks in advance.

like image 586
Gog Avagyan Avatar asked Jul 24 '15 12:07

Gog Avagyan


1 Answers

First of all, there's no guarantees that the clipboard actually has any data on it at all - for example, when you first turn on your phone, you'd expect the clipboard to be empty. Secondly, if there is data, you need to check if it is in the right format. It doesn't make sense to try to paste an image into a textbox.

If there is no content, then clipboard.getPrimaryClip() will return null. If there is content, but it isn't text (a URL, for example, is treated differently to text), then item.getText() will return null. This is causing an exception in your code, because you are calling toString() on a null reference.

The Android developer docs show a short sample, a bit like this:

if (clipboard.hasPrimaryClip()
    && clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))
{
    // Put your paste code here
}

But as I have mentioned, certain things, like a URL, will not match this pattern, even though they could be safely converted to text. To handle all these things, you can try this:

if (clipboard.hasPrimaryClip())
{
    ClipData data = clipboard.getPrimaryClip();
    if (data.getItemCount() > 0)
    {
        CharSequence text = data.getItemAt(0).coerceToText(this);
        if (text != null)
        {
            // Put your paste-handling code here
        }
    }
}
like image 99
Andrew Williamson Avatar answered Sep 20 '22 16:09

Andrew Williamson