Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClipData getPrimaryClipDescription() returning null in Android 6.0.1

Tags:

android

if (mClipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
            mClipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML))

getPrimaryClipDescription() is null in few Android 6.0.1.

Attempt to invoke virtual method 'boolean android.content.ClipDescription.hasMimeType(java.lang.String)' on a null object reference

Update

Please try on devices like Samsung Galaxy S5 and Note 4.

like image 785
mihirjoshi Avatar asked Jul 12 '16 05:07

mihirjoshi


2 Answers

I tested this code on Galaxy S6 - 6.0.0 image using Genymotion emulator and I did not receive any errors.

       // Copy to clipbaord
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
       // ClipData clip = ClipData.newPlainText("Label", "TEXT");
       // clipboard.setPrimaryClip(clip);

        if (clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
                clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML))
        {
            Log.d("Copied!", "Copied!");
        }

Few suggestions:

  1. Check that mClipboard is instantiated.
  2. I have tested the code with ClipData clip and setPrimaryClip lines commented and un-commented with no errors. However, you can test your code by adding these lines if you dont have them already.
  3. hasMimeType() and getPrimaryClipDescription() have been added to Android since API 11, so there is no reason for Samsung to disable them (without providing sufficient error message).
  4. Try to add this code before your main code:

    if (!(mClipboard .hasPrimaryClip()))

    This will ensure that the clipboard has a primary clip that you can handle.

  5. Check this link from Android website: https://developer.android.com/guide/topics/text/copy-paste.html It has good information and code on copying and pasting content.

  6. Finally, contact Samsung. You can post a question on Samsung Developers Community http://developer.samsung.com/community to check the source of the problem since this issue is specific to Samsung devices.

like image 114
Kalimah Avatar answered Sep 30 '22 06:09

Kalimah


Before attempting that method you can check it has PrimaryClip or not.

if(mClipboard.hasPrimaryClip()  && (mClipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||  mClipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML)))

that can be a good way to avoid null pointer exception.

like image 33
RBK Avatar answered Sep 30 '22 08:09

RBK