skip to Main Content

I copy photos or videos to another folder using the following codes:

override fun onButtonClick(position: Int) {
    val origin = File(statuses[position]) // Addresses of photos or videos are stored in the mutable list of statuses
    val destination = if (statuses[position].endsWith(".jpg"))
        File(Environment.getExternalStorageDirectory().path + '/' + Environment.DIRECTORY_PICTURES + FilePath.PICTURES_DIRECTORY + '/' + Random.nextInt() + ".jpg")
    else File(Environment.getExternalStorageDirectory().path + '/' + Environment.DIRECTORY_MOVIES + FilePath.VIDEO_DIRECTORY + '/' + Random.nextInt() + ".mp4")
    origin.copyTo(destination)
}

The file is copied and shown in the file manager.
But I can’t find that copied file in gallery.
How can I show it in the gallery?

2

Answers


  1. I think this is the way:

    
           val appDirectoryName = "XYZ"
                val imageRoot = File(
                    Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES
                    ), appDirectoryName
                )
    
    

    This creates a new file in the gallery and give you the root for the location

    AKA: destination

    Login or Signup to reply.
  2. Did you try to use the MediaScannerConnection class to notify the media scanner about the new file?

    override fun onButtonClick(position: Int) {
    val origin = File(statuses[position])
    val destination = if (statuses[position].endsWith(".jpg"))
        File(Environment.getExternalStorageDirectory().path + '/' + Environment.DIRECTORY_PICTURES + FilePath.PICTURES_DIRECTORY + '/' + Random.nextInt() + ".jpg")
    else File(Environment.getExternalStorageDirectory().path + '/' + Environment.DIRECTORY_MOVIES + FilePath.VIDEO_DIRECTORY + '/' + Random.nextInt() + ".mp4")
    origin.copyTo(destination)
    
    // Notify the media scanner about the new file
    MediaScannerConnection.scanFile(
        applicationContext,
        arrayOf(destination.absolutePath),
        null,
        null
    )
    }
    

    and don’t forget to add the necessary permission

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    I hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search