Search code examples
javaandroidclipboardclipboardmanager

JavaSecurityException using ClipData on Android


I am trying to paste text using ClipData on Android. The following code gives a java.lang.SecurityException. This does not happen all of the time. Should I declare any uses-permission to read the clipboard?

java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2750)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2811)
at android.app.ActivityThread.-wrap12 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1528)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6316)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:762)
Caused by: java.lang.SecurityException:
at android.os.Parcel.readException (Parcel.java:1683)
at android.database.DatabaseUtils.readExceptionFromParcel (DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel (DatabaseUtils.java:146)
at android.content.ContentProviderProxy.openTypedAssetFile (ContentProviderNative.java:692)
at android.content.ContentResolver.openTypedAssetFileDescriptor (ContentResolver.java:1163)
at android.content.ContentResolver.openTypedAssetFileDescriptor (ContentResolver.java:1107)
at android.content.ClipData$Item.coerceToText (ClipData.java:332)
at br.com.sicoob.camera.clipboard.ClipboardInterface.getText (ClipboardInterface.java:35)
at br.com.sicoobnet.InicioWap.verificarExisteBoletoCopiado (InicioWap.java:312)
at br.com.sicoobnet.InicioWap.verificarAcao (InicioWap.java:308)
at br.com.sicoobnet.InicioWap.onCreate (InicioWap.java:126)
at android.app.Activity.performCreate (Activity.java:6757)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2703)

Solution

  • This question is fixed to my project, but to everyone who whants to know, this is how I fix.

    First I figured out when this error happens. It was when I don't have any text in clipboard and my application tried to go to external storage and the error was thrown.

    Then to fix that I just change my method to verify has a text inside clipboard.

    It was like that:

    ClipboardManager clipboard = getManager(context);
    ClipData clip = clipboard.getPrimaryClip();
    return clip != null && clip.getItemCount() > 0;
    

    Then it was like that:

    ClipboardManager clipboard = getManager(context);
    clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);