4

I am getting { text/plain {NULL} } when I am using ClipData but if I use deprecated method mClipboard.getText() it is working just fine.

if (mClipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
    ClipData clipData = mClipboard.getPrimaryClip();
    ClipData.Item item = clipData.getItemAt(0);
    Log.d(TAG, clipData.toString());
    Log.d(TAG, mClipboard.getText());
}

Update

Issue exists in Samsung galaxy Tab 3.

Samsung Galaxy Tab 3

mihirjoshi
  • 12,161
  • 7
  • 47
  • 78
  • Hey unable to reproduce this issue. I just copied and past your code and tested on a device it runs as supposed to. here is a screenshot http://imgur.com/EBPsLVP How do you copy the data and have you tested it on a real device? – ProblemSlover Nov 07 '15 at 07:27
  • @ProblemSlover It is coming on Samsung Galaxy S4 and Galaxy Tab. I'll post the screenshot tomorrow. – mihirjoshi Nov 08 '15 at 09:34
  • Was my answer helpful for you? – ProblemSlover Nov 12 '15 at 06:52
  • @ProblemSlover Not really. In any case `ClipData.Item` is coming null. So `item.coerceToText(this)` and `item.getText()` are both null. – mihirjoshi Nov 12 '15 at 07:19

1 Answers1

5

The reason of your problem is unknown. since it works on a device which I tested on (S6 5.0). You may want to look at the implementation of deprecated getText() method:

public CharSequence getText() {
    ClipData clip = getPrimaryClip();
    if (clip != null && clip.getItemCount() > 0) {
        return clip.getItemAt(0).coerceToText(mContext);
    }
    return null;
}

In order to obtain the text It uses the method coerceToText() . according to description of this method:

     * Turn this item into text, regardless of the type of data it
     * actually contains.

Therefore , I presume the deprecation of method getText() is due to a performance concern or something else.

Anyway. Since method getText() uses API which is not deprecated, as a workaround you can use some part of the source of this method(specifically, method coerceToText() ) if calling recommended API returns null:

ClipboardManager mclipboard =(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
boolean isTextPlain = mclipboard.getPrimaryClip().getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
    CharSequence text = null;
if (isTextPlain){
    ClipData clipData = mclipboard.getPrimaryClip();
    ClipData.Item item = clipData.getItemAt(0);
    if (  item!= null ){
        text = item.getText();
        if (text == null){
            // taken from source of clipData.getText() method
            text =  item.coerceToText(this);
        }
    }
}
ProblemSlover
  • 2,538
  • 2
  • 23
  • 33