Skip to content Skip to sidebar Skip to footer

Mediastore.mediacolumns.data Is Deprecated, And I Want To Load Images From Gallery To My App

I want to load all the pictures from the galley to my app by using MediaStore.MediaColumns.DATA , but it is deprecated. So, what is the other way to load them? I use this code now,

Solution 1:

I was able to replace MediaStore.MediaColumns.Data with its own file ID (incredibly, files have IDs) and correctly constructing its URI, like this:

fungetAllShownImagesPath(activity: Activity): MutableList<Uri> {
    val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexID: Intval listOfAllImages: MutableList<Uri> = mutableListOf()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    var imageId: Long
    cursor = activity.contentResolver.query(uriExternal, projection, null, null, null)
    if (cursor != null) {
        columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()) {
            imageId = cursor.getLong(columnIndexID)
            val uriImage = Uri.withAppendedPath(uriExternal, "" + imageId)
            listOfAllImages.add(uriImage)
        }
        cursor.close()
    }
    return listOfAllImages
}

and then with Uri you build it in your Views!

Solution 2:

I managed to come up with the following solution, its kind of an addition to the previous answer

but there I still couldn't load images with the obtained Uri. Documentation suggested to use openFileDescriptor() which I did and then decoded images' bitmaps from it:

overridefunloadImagesFromStorage(): List<AdapterImage> {

    val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexId: Intval listOfAllImages = mutableListOf<AdapterImage>()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    cursor = context.contentResolver
        .query( uri, projection, null, null, null)

    if ( cursor != null ){
        columnIndexId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()){

            val contentUri = ContentUris.withAppendedId(uri, cursor.getLong(columnIndexId))

            //here I open FileDescriptor and then decode it into Bitmapvar image: Bitmap
            context.contentResolver.openFileDescriptor(contentUri, "r").use { pfd ->
                if( pfd != null ){
                    image = BitmapFactory.decodeFileDescriptor(pfd.fileDescriptor)
                    listOfAllImages.add(AdapterImage(image))
                }
            }

        }
        cursor.close()
    }

    return listOfAllImages
}

P.S. My method will return a list of AdapterImage objects that I use later in app but you can put anything you need there at this point

Solution 3:

I finally solved the problem by creating this class

classFileHelper{
val mediaType = "multipart/form-data".toMediaTypeOrNull()

fungetPartBodyFromUri(context: Context, uri: Uri): MultipartBody.Part {
    val realPath = getPathFromURI(context, uri)
    val fileImage = createFile(realPath)
    val requestBody = createRequestBody(fileImage)
    return createPart(fileImage, requestBody)
}

privatefuncreateFile(realPath: String): File {
    return File(realPath)
}

privatefuncreateRequestBody(file: File): RequestBody {
    return file.asRequestBody(mediaType)
}

privatefuncreatePart(file: File, requestBody: RequestBody): MultipartBody.Part {
    return MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
}

privatefungetPathFromURI(context: Context, uri: Uri): String {
    var realPath = String()
    uri.path?.let { path ->

        val databaseUri: Uri
        val selection: String?
        val selectionArgs: Array<String>?
        if (path.contains("/document/image:")) { // files selected from "Documents"
            databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            selection = "_id=?"
            selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
        } else { // files selected from all other sources, especially on Samsung devices
            databaseUri = uri
            selection = null
            selectionArgs = null
        }
        try {
            val column = "_data"val projection = arrayOf(column)
            val cursor = context.contentResolver.query(
                databaseUri,
                projection,
                selection,
                selectionArgs,
                null
            )
            cursor?.let {
                if (it.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(column)
                    realPath = cursor.getString(columnIndex)
                }
                cursor.close()
            }
        } catch (e: Exception) {
            println(e)
        }
    }
    return realPath
}

}

Media.DATA it's deprecate and "MediaStore.Images.Media._ID" to get the correct column, not working so I create column I need

valcolumn="_data"valprojection= arrayOf(column)

then I use getColumnIndexOrThrow() method to get correct index

valcolumnIndex= cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)

Solution 4:

In Java

FileInputStreaminput=null;
    FileOutputStreamoutput=null;
    try {
        StringfilePath=newFile(getCacheDir(), "tmp").getAbsolutePath();
        android.os.ParcelFileDescriptorpfd= getContentResolver ().openFileDescriptor(
            sharedFileUri, "r");
        if (pfd != null) {
            FileDescriptorfd= pfd . getFileDescriptor ();
            input = newFileInputStream (fd);
            output = newFileOutputStream (filePath);
            int read;
            byte[] bytes = newbyte[4096];
            while ((read = input.read(bytes)) != -1) {
                output.write(bytes, 0, read);
            }
            FilesharedFile=newFile(filePath);
            StringfinalPath= sharedFile.getPath();
        }
    }catch(Exception ex) {
    } finally {
        try {
            input.close();
            output.close();
        } catch (Exception ignored) {
        }
    }

Solution 5:

you can use "IMediaColumns" instead of "MediaColumns".

Post a Comment for "Mediastore.mediacolumns.data Is Deprecated, And I Want To Load Images From Gallery To My App"