Reputation: 4283
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
Upvotes: 8
Views: 3752
Reputation: 1
ClipboardManager cm = (ClipboardManager)getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData=ClipData.newPlainText("label",key.getText().toString());
cm.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(), "Copied :)", Toast.LENGTH_SHORT).show();
Upvotes: -1
Reputation: 569
Use below code
String copyString = clipboard.getPrimaryClip().getItemAt(0).getText()
Upvotes: 5
Reputation: 1007296
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.
Upvotes: 9