javaandroidcopy-pasteclipboardmanager

Unable to get the clipboard data in java android


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?


Solution

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