1

I am working on a android project in java where i need to copy paste some data in an activity, but the problem here is i am able to set the primary clip but when i try to access the primaryClip it returns false. Im setting the Primary clip using the following code,

ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);
 ClipData clip = ClipData.newPlainText("textData","12345");
 clipboard.setPrimaryClip(clip);

Im trying to access like this

 ClipboardManager clipboard = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
 if (clipboard.hasPrimaryClip()) {
 //This returning false
 }

Here hasPrimaryClip() is returning false, But if i open any text editor application and try to paste their it will paste the data that i have set as primary Clip.

How to resolve this error?

asked Oct 27, 2021 at 8:23

2 Answers 2

3

Try calling clipboard.hasPrimaryClip() 100ms after clipping the data and that should work.

 val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
 val clip = ClipData.newPlainText("label", "whatever")
 clipboard.setPrimaryClip(clip)
 Log.d(TAG, clipboard.primaryClip?.getItemAt(0).toString())

Gives null but:

 val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
 val clip = ClipData.newPlainText("label", "whatever")
 clipboard.setPrimaryClip(clip)
 Handler().postDelayed({
 Log.d(TAG, clipboard.primaryClip?.getItemAt(0).toString())
 },100)

Prints "whatever".

answered Oct 27, 2021 at 8:49
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, This solved my problem
1

As official docs says, it returns false if the application isn`t the default IME. https://developer.android.com/reference/android/content/ClipboardManager#hasPrimaryClip()

answered Oct 27, 2021 at 8:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.