Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android clipboard.getText() is deprecated; how then to get the text item that's in it?

This works fine, showing me exactly what was the last string put into Android clipboard, which happens to be euswcnmst.

Log.w("clip", clipboard.getText().toString());

But getText is deprecated for clipboard objects.

Meanwhile, if I do Log.w("clip", clipboard.getPrimaryClip().toString());, I get this, exactly as shown ClipData { text/plain "label" {T:euswcnmst} }

I see what I want, and, assuming this format is always used for string clipboard items, I can use String functions (find : and subsequent } and do substring) to extract euswcnmst, but that's a hack.

What SHOULD I do?

EDIT

Based on Commonsware's Answer, here's what I should do:

ClipData clip = clipboard.getPrimaryClip();

if(clip == null || clip.getItemCount() == 0)
  return; // ... whatever; just don't go to next line

String t = clip.getItemAt(0).getText().toString();

EDIT 2

If the last ITEM in the clipboard was NOT text, the above code gives this error:

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

Here's the fix (I added the third line below):

if(   clip == null 
   || clip.getItemCount() == 0 
   || clip.getItemCount() > 0 && clip.getItemAt(0).getText() == null
  )
    return; // ... whatever; just don't go to next line
like image 883
DSlomer64 Avatar asked May 12 '16 20:05

DSlomer64


1 Answers

Please understand that the clipboard is not purely for text. Complex constructs can be placed on the clipboard, in the form of 1 to N ClipData.Item objects inside the ClipData object that you are getting from getPrimaryClip().

Given your ClipData, call getItemCount() to determine the number of items. For whichever item(s) you wish to attempt to use, call getItemAt() on the ClipData to get the corresponding ClipData.Item. On that item, you can call getText() or coerceToText() to try to get a text representation of that item.

like image 184
CommonsWare Avatar answered Oct 30 '22 19:10

CommonsWare