Home > Software engineering >  Android file.exists() and file.isFile not working
Android file.exists() and file.isFile not working

Time:11-16

I try to download a file to downloads folder with this code:

private fun downloadTrack(track: Track) {
        val url = track.file
        val request = DownloadManager.Request(Uri.parse(url))
        request.setDescription("Downloading track ${track.trackName}...")
        request.setTitle(track.trackName)
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

        request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS,
            track.trackName   ".mp3"
        )

        val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        val downloadId: Long = manager.enqueue(request)
        registerBroadcast(downloadId)
    }

And after it was downloaded on following logins I'm trying to check if it already exists with this code:

    private fun getTrack(track: Track) {
        val file =
            File(
                Environment.DIRECTORY_DOWNLOADS,
                track.trackName   ".mp3"
            )

        try {
            if (file.isFile) {
                Toast.makeText(this, "FILE EXISTS", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "FILE NOT FOUND", Toast.LENGTH_SHORT).show()
                downloadTrack(track)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Also tried file.exists() and playing with directories. Nothing helps, file can't be found after it was downloaded though I'm looking for it in the same directory. Help please.

CodePudding user response:

Environment.DIRECTORY_DOWNLOADS

That is not enough.

You need :

getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS)
  • Related