首页 > 解决方案 > 在android中获取内容提供者uri崩溃

问题描述

我的设备上有以下文件路径

file:///storage/emulated/0/DCIM/IMG_20190206_141330.jpg

我正在尝试让内容提供者能够在 kotlin 中使用这种方法来旋转它

private fun Uri.getPath(ctx: Context): String? {
    val projection = arrayOf(MediaStore.Images.Media.DATA)
    val cursor = ctx.contentResolver.query(this, projection, null, null, null) ?: return null
    val columnIndex = cursor.getColumnIndexOrThrow(projection[0])
    cursor.moveToFirst()
    val s = cursor.getString(columnIndex)
    cursor.close()
    return s
}

我收到以下崩溃

 java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native(Native Method)
        at android.util.Log.i(Log.java:198)
        at com.forsale.app.utils.UriExtensionsKt.rotateImageIfRequired(UriExtensions.kt:80)
        at com.forsale.app.features.postad.basicinformation.PostAdBasicInformationFragment$onActivityResult$$inlined$let$lambda$1.invokeSuspend(PostAdBasicInformationFragment.kt:254)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:236)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6938)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

有人可以帮忙吗?

标签: androidkotlin

解决方案


我正在尝试为其获取内容提供商

那是行不通的。内容Uricontent://作为方案。你file://的计划是这样的。

让它能够旋转它

您可以摆脱Uri.getPath()(这不适用于大多数Uri值,即使是那些有content://方案的值)。使用openInputStream()on aContentResovler打开InputStream由 标识的内容Uri(适用于两者content://file:// Uri值)。然后,使用它InputStream来读取图像以旋转它。


推荐阅读