androidfileandroid-download-manager

Check If File Exists Before downloading the file


I am using download manager to download the file. The code for downloading the file is as follow.

   private String DownloadData(Uri uri, View v, String textview) {

    long downloadReference;

    // Create request for android download manager
    dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    //Setting title of request
    request.setTitle(textview);

    //Setting description of request
    request.setDescription("Android Data download using DownloadManager.");

    //Set the local destination for the downloaded file to a path within the application's external files directory
    request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");

    //Enqueue download and save into referenceId
    downloadReference = dm.enqueue(request);

    return null
}

The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is

   String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));

                File file = new File(path);

                if(file.exists()){
                    Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
                } else if (!file.exists()) {
                    Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
                   Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
                   String filepath = DownloadData(uri,view,filename);
                }

but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,


Solution

  • I detected some strange behavior with exists time ago and changed it to isFile:

    File file = new File(path);
    if (file.isFile()) {
        Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
        // ...
    }
    

    I think the mobile, somehow, created a directory every time new File() was executed. Check this.