Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - 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, but it is deprecated as I said:

fun getAllShownImagesPath(activity: Activity): MutableList<String> {
    val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexData: Int
    val listOfAllImages: MutableList<String> = mutableListOf()
    val projection = arrayOf(MediaStore.MediaColumns.DATA)
    var absolutePathOfImage: String
    cursor = activity.contentResolver.query(uri, projection, null, null, null)
    if (cursor != null) {
        columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(columnIndexData)
            listOfAllImages.add(absolutePathOfImage)
        }
        cursor.close()
    }
    return listOfAllImages
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

fun getAllShownImagesPath(activity: Activity): MutableList<Uri> {
    val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexID: Int
    val 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...