Skip to content Skip to sidebar Skip to footer

Android Getting File Path From Content Uri Using Contentresolver

I'm trying to get the file path for a content URI. URL looks like this: content://com.android.providers.downloads.documents/document/31 The cursor object is not null but the c

Solution 1:

I'm trying to get the file path for a content URI

There is no requirement that a content://Uri point to a file, let alone one that you can access. If you want to access the data in the file, use a ContentResolver and openInputStream() or openOutputStream().

Solution 2:

This helper class can help, i found online in a github library

import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.webkit.MimeTypeMap
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale.getDefault

/**
 * This class will create a temporary file in the cache if need.
 *
 * When the uri already have `file://` schema we don't need to create a new file.
 * The temporary file will always override a previous one, saving memory.
 * Using the cache memory(context.cacheDir) we guarantee to not leak memory
 *
 * @param context used to access Android APIs, like content resolve, it is your activity/fragment.
 * @param uri the URI to load the image from.
 * @param uniqueName If true, make each image cropped have a different file name, this could cause
 * memory issues, use wisely.
 *
 * @return string value of the File path.
 */fungetFilePathFromUri(context: Context, uri: Uri, uniqueName: Boolean): String =
    if (uri.path?.contains("file://") == true) uri.path!!
    else getFileFromContentUri(context, uri, uniqueName).path

privatefungetFileFromContentUri(context: Context, contentUri: Uri, uniqueName: Boolean): File {
    // Preparing Temp file nameval fileExtension = getFileExtension(context, contentUri) ?: ""val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", getDefault()).format(Date())
    val fileName = ("temp_file_" + if (uniqueName) timeStamp else"") + ".$fileExtension"// Creating Temp fileval tempFile = File(context.cacheDir, fileName)
    tempFile.createNewFile()
    // Initialize streamsvar oStream: FileOutputStream? = nullvar inputStream: InputStream? = nulltry {
        oStream = FileOutputStream(tempFile)
        inputStream = context.contentResolver.openInputStream(contentUri)

        inputStream?.let { copy(inputStream, oStream) }
        oStream.flush()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        // Close streams
        inputStream?.close()
        oStream?.close()
    }

    return tempFile
}

privatefungetFileExtension(context: Context, uri: Uri): String? =
    if (uri.scheme == ContentResolver.SCHEME_CONTENT)
        MimeTypeMap.getSingleton().getExtensionFromMimeType(context.contentResolver.getType(uri))
    else uri.path?.let { MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(it)).toString()) }

@Throws(IOException::class)privatefuncopy(source: InputStream, target: OutputStream) {
    val buf = ByteArray(8192)
    var length: Intwhile (source.read(buf).also { length = it } > 0) {
        target.write(buf, 0, length)
    }
}

Post a Comment for "Android Getting File Path From Content Uri Using Contentresolver"