Adha Fajri
Adha Fajri

Reputation: 41

Android file exists() not working

Right now I'm currently trying to make a file downloaded from a Uri, but I wanna make it so that if the file has been downloaded it's wont be able to download it anymore. So i decided to use file.exists() to do that, But right now the file.exists() method isn't working for some reason.

Uri uri = Uri.parse("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf");

Uri path = Uri.parse("file:///storage/emulated/0/Download/");
String test = uri.getPath();
File file = new File(path.getPath());
File check = new File(path.getPath()+uri.getLastPathSegment());
if (!check.exists()||!check.isFile()) {
  DownloadManager.Request request = new DownloadManager.Request(uri);
  request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  request.setDestinationInExternalPublicDir(String.valueOf(file), uri.getLastPathSegment());
  Long reference = downloadManager.enqueue(request);
}
Intent intent = new Intent(MainActivity.this,ViewActivity.class);
intent.putExtra("book",""+uri.getLastPathSegment()+"");
startActivity(intent);

I try to do a file check and see if file exist or not, but I always get file doesn't exist even though the file is already downloaded and on the right place. Can someone help me with this?

Upvotes: 1

Views: 3534

Answers (2)

Sagar
Sagar

Reputation: 24907

Instead of :

request.setDestinationInExternalPublicDir(String.valueOf(file), uri.getLastPathSegment());

Use:

 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, uri
                    .getLastPathSegment());

Reason:

setDestinationInExternalPublicDir is expecting dirType as your first parameter:

But when set it to String.valueOf(file) it will store the file in /storage/emulated/0/storage/emulated/0/Download/lesson2.pdf instead of storage/emulated/0/Download/. As a result your condition always fails.

Upvotes: 0

Eugene Kartoyev
Eugene Kartoyev

Reputation: 511

if (!check.exists()||!check.isFile()) - is not good, as, in theory, it may trigger on a folder that has a name lessons2.pdf. So, isFile() alone should suffice.

Make sure you have all the permissions in Manifest

android.permission.WRITE_EXTERNAL_STORAGE

and that you have asked for read/write permissions runtime, too.

and access the downloads folder through

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();

because it may be emulated/0/Downloads or it maybe different, depending on whether the phone is used in a guest mode.

and name

String name = Uri.parse("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf").getLastPathSegment();`

then do your check with

File check = new File(path, name);

Upvotes: 1

Related Questions