Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Android Clipboard (text) when opening an app?

I am making an app and eventually I want to check the clipboard's content right when user opens my app with a regex in order to offer an action. I'm currently trying to be sure that I get the data properly by displaying it in a Toast.

I am using ClipboardManager on my MainActivity's OnCreate function as described in the official documentation and many other places, although I get a null pointer error when trying to access clipboard's data.

But, if I set a delay of 1-2 seconds before trying to get that data (I use handler.postDelayed for the delayed action), I can read the clipboard's content properly, which is odd...

Why does that happen and how to access clipboard's data without any delay, right when app is opened?

The code I use is:

ClipboardManager clipboardManager = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);;
ClipData clipData = clipboardManager.getPrimaryClip();
ClipData.Item item = clipData.getItemAt(0);
String clipText = item.getText().toString();
Toast.makeText(getApplicationContext(), clipText, Toast.LENGTH_SHORT).show();

And it crashes in 3rd line with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ClipData$Item android.content.ClipData.getItemAt(int)' on a null object reference

Thank you

like image 893
Spyros G Avatar asked Oct 19 '25 09:10

Spyros G


1 Answers

As of Android 10 and later, your app needs to have input focus to read clipboard successfully. Otherwise getPrimaryClip() returns null.

onCreate() is too early for your activity to have input focus. You can override onWindowFocusChanged() to attempt to read the clipboard as soon as there is focus.

like image 118
laalto Avatar answered Oct 21 '25 01:10

laalto



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!