Home > Blockchain >  Unable to get the clipboard data in java android
Unable to get the clipboard data in java android

Time:10-27

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?

CodePudding user response:

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

CodePudding user response:

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".

  • Related