S.P. Soni
S.P. Soni

Reputation: 39

How to check particular file is exist in our cellphone's "Download" Directory

I have created one android app in which I have provided features of download attachment and I want to change the text of the download button from Download to View once the file is downloaded or already present in the Downloads directory of my mobile. For this, I need code in Kotlin to check whether a particular file is present in the Download directory or not.

Upvotes: 0

Views: 47

Answers (2)

Pawan Soni
Pawan Soni

Reputation: 936

If you want to look the file which you have already saved.

create a variable and save the file Path at the time of Saving file. When tried to save another file, get the previous one name and compare in this case if same name it will provde an error.

File is already saved in the internal storage.

    if (PdfForSmartCartridges.sFilePAATh != "") {

if(PdfForSmartCartridges.sFilePAATh!="NewPath"){
                        val myFile = File(PdfForSmartCartridges.sFilePAATh)
                        val intent = Intent(Intent.ACTION_VIEW)
                        intent.setDataAndType(
                            Uri.fromFile(myFile),
                            context.getString(R.string.application_pdf)
                        )
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        context.startActivity(intent)
}
                    }

Upvotes: 0

tohid noori
tohid noori

Reputation: 221

At first check the manifest permissions is important and then accept them in the app.

Manifest

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

MainActivity

class MenuActivity : AppCompatActivity(){

   internal var isExist: Boolean? = false
   internal var file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val filesInSideOfDownloadDirectory = Arrays.asList(*file.list()!!) //this code puts file names in the download directory to the list
        for (i in filesInSideOfDownloadDirectory.indices) {
            if (filesInSideOfDownloadDirectory[i] == "YOUR_FILE_NAME") {
                isExist = true
            } else {
                isExist = false
            }
        }

        if (isExist!!) {
            Toast.makeText(this@MenuActivity, "The File Is Exist", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(this@MenuActivity, "The File Is Not Exist", Toast.LENGTH_LONG).show()
        }

Upvotes: 1

Related Questions