首页 > 解决方案 > Android ContentResolver.insert() 抛出 NullPointerException

问题描述

我正在尝试将一些音频文件(m4a、mp3、...)添加到 MediaStore 的音频收藏中,以便其他音乐应用程序可以列出它们。为了简单起见,我只是复制了文档中的内容。(https://developer.android.com/training/data-storage/shared/media

所以在 onCreate() 方法的活动中我写了这个:

val resolver = applicationContext.contentResolver

val audioCollection =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        MediaStore.Audio.Media.getContentUri(
            MediaStore.VOLUME_EXTERNAL_PRIMARY
        )
    } else {
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    }

val songDetails = ContentValues().apply {
    put(MediaStore.Audio.Media.DISPLAY_NAME, "Test Track")
}

resolver.insert(audioCollection, songDetails)

但是每次我启动它时,我都会得到以下信息:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference
        at android.os.Parcel.createException(Parcel.java:1972)
        at android.os.Parcel.readException(Parcel.java:1934)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
        at android.content.ContentProviderProxy.insert(ContentProviderNative.java:476)
        at android.content.ContentResolver.insert(ContentResolver.java:1593)

清单声明了 READ、WRITE 以及 MANAGE_EXTERNAL_STORAGE 权限,并在我设备上的 android 应用设置中启用了这些存储权限。

标签: androidkotlinnullpointerexceptioninsertandroid-contentresolver

解决方案


推荐阅读