Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null from Clipboard

I need to get copied data from clipboard. I use this code:

val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clipData: ClipData? = clipboardManager.primaryClip
clipData?.let { textView.text = clipData.getItemAt(0).text }

If I use this code inside onCreate() or onResume() callbacks, I always getting null from clipboard.

But if I call this code:

textView.post {
        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clipData: ClipData? = clipboardManager.primaryClip
        clipData?.let { textView.text = clipData.getItemAt(0).text }
}

I get copied string.

So, I make conclusion, that Clipboard waits until all views are rendered.

Why clipboard needs to wait for rendering all views? Or maybe clipboard is waiting for something else

like image 938
Sergei Buvaka Avatar asked Jun 18 '26 12:06

Sergei Buvaka


1 Answers

It is happening because your app should be in focus when you try to get primaryClip from Clipboard.

All views have to be set up and tied to activity, that's why you have to add your function to UI queue with help of view.post { }

That change was added in API 29 👇🏻 https://developer.android.com/about/versions/10/privacy/changes#clipboard-data

like image 157
Nikolay Grebnev Avatar answered Jun 22 '26 22:06

Nikolay Grebnev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!