Android – use getprimaryclip() to copy the given data, given {text / plain {null}}
I get the information of {text / plain {null}} when using clipdata, but if I use the deprecated method mclipboard. Gettext(), it will work normally
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 information
There is a problem in Samsung Galaxy label 3
resolvent:
The cause of your problem is unknown. Because it can run on the device I tested (S6 5.0). You may need to check the implementation of the deprecated gettext() method:
public CharSequence getText() {
ClipData clip = getPrimaryClip();
if (clip != null && clip.getItemCount() > 0) {
return clip.getItemAt(0).coerceToText(mContext);
}
return null;
}
To get text, it uses the coercetotext() method. According to the description of this method:
* Turn this item into text, regardless of the type of data it
* actually contains.
Therefore, I don't think the use of gettext () method is due to performance problems or other reasons
In any case, since the method gettext() uses the deprecated API, as a solution, if calling the suggested API returns null, you can use the source of some parts of this method (specifically, the method coercetotext()):
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);
}
}
}