0

Trying to show toast if file already exist into SDCard, but seems condition not works for me

public void startDownload(View v) {

     if(hasAudio.equals("no"))
        {
            Toast.makeText(getApplicationContext(), "MP3 not Available !", Toast.LENGTH_LONG).show();
        }
     else if(hasAudio.equals("yes"))             
        {
         File file = new File(getExternalCacheDir() + "Audios", title + ".mp3" );
         if (file.exists()) 
         {
           Toast.makeText(getApplicationContext(), "Already downloaded !", Toast.LENGTH_LONG).show();
         }
         else 
         {
            Uri uri=Uri.parse(download);
            mgr.enqueue(new DownloadManager.Request(uri)
                .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                                        DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false)
                .setTitle(title)
                .setDestinationInExternalPublicDir("Audios", title + ".mp3"));

            v.setEnabled(false);
          }         
     }
}

whenever i do tap on button, its start downloading mp3, no matter already exist or not, but i want to show the toast if file already exist in SD Card

Sun
  • 6,768
  • 25
  • 76
  • 131
  • 1
    Are you sure you mean to check `getExternalCacheDir()` and not `getExternalFilesDir()`? – Ken Wolf Mar 18 '14 at 07:45
  • My suggestion is to check file size instead of just checking if it exists. So that even if download gets interrupted due to network failures(and corrupt file still exists), it works. – Seshu Vinay Mar 18 '14 at 07:46
  • @SeshuVinay hey i agree with you, can you show me the way ? – Sun Mar 18 '14 at 08:49

1 Answers1

0

Then Why do you need else condition, remove it

public void startDownload(View v) {

 if(hasAudio.equals("no"))
    {
        Toast.makeText(getApplicationContext(), "MP3 not Available !", Toast.LENGTH_LONG).show();
    }
 else if(hasAudio.equals("yes"))             
    {
     File file = new File(getExternalCacheDir() + "Audios", title + ".mp3" );
     if (file.exists()) 
     {
       Toast.makeText(getApplicationContext(), "Already downloaded !", Toast.LENGTH_LONG).show();
     }else{
       Toast.makeText(getApplicationContext(), "Not Exist !", Toast.LENGTH_LONG).show();
     }


 }
}
John
  • 8,846
  • 8
  • 50
  • 85
  • see this may be help to you http://stackoverflow.com/questions/7697650/check-if-file-exists-on-sd-card-on-android. also see http://stackoverflow.com/questions/7817551/how-to-check-file-exist-or-not-and-if-not-create-a-new-file-in-sdcard-in-async-t – user3355820 Mar 18 '14 at 07:52