akexorcist / ScreenshotDetection

[Android] Screenshot detection while user using your app
Apache License 2.0
160 stars 33 forks source link

android.database.CursorIndexOutOfBoundsException #9

Open wahyukharisma opened 2 years ago

wahyukharisma commented 2 years ago

I found this error in some devices like Samsung, Xiaomi, Oppo, and Realme

com.akexorcist.screenshotdetection.ScreenshotDetectionDelegate.getFilePathFromContentResolver (ScreenshotDetectionDelegate.kt:142) com.akexorcist.screenshotdetection.ScreenshotDetectionDelegate.onContentChanged (ScreenshotDetectionDelegate.kt:107) com.akexorcist.screenshotdetection.ScreenshotDetectionDelegate.access$onContentChanged (ScreenshotDetectionDelegate.kt:32) com.akexorcist.screenshotdetection.ScreenshotDetectionDelegate$startScreenshotDetection$1$invokeSuspend$$inlined$collect$1.emit (Collect.kt:133) kotlinx.coroutines.flow.FlowKt__DelayKt$debounceInternal$1$3$1.invokeSuspend (Delay.kt:235)

jason-hwang commented 2 years ago

Same here.

I've fixed the related codes like this:

@Suppress("DEPRECATION")
private fun getFilePathFromContentResolver(context: Context, uri: Uri): String? {
    try {
        context.contentResolver.query(
          ...
        )?.let { cursor ->
            cursor.moveToFirst()
            if (cursor.count > 0) {
                val columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA)
                var path: String? = null
                if (columnIndex > 0) {
                    path = cursor.getString(columnIndex)
                }
                cursor.close()
                return path
            }
            cursor.close()
            return null
        }
    } catch (e: Exception) {
        Log.w(TAG, e.message ?: "")
    }
    return null
}

How about this idea? to fix the exception.