Check whether the file is already exists Android not working - android

I want to check whether the file is already exists in Download folder in Android. I'm using Android download manager to download the file. In there if section is not working. If file is already there (Ex: File name - songname.mp3), when downloading the same file for the second time it's downloading the file as songname1.mp3. I have tried the code below. I want to show a message if the file is already there.
Please help me to fix this issue.
public void DownloadChecker() {
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
} else {
String servicestring = Context.DOWNLOAD_SERVICE;
DownloadManager downloadmanager;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(DownloadUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(MainActivity.this,
Environment.DIRECTORY_DOWNLOADS,"mysongs.mp3");
Long reference = downloadmanager.enqueue(request);
}
}

change
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
to
if(applictionFile.canRead()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
or
if(applictionFile.isFile()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}

Try in simple way
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do your code stuff
}

You should probably try changing:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
to:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "mysongs.mp3");

on which testing device are you testing your app? is it above api-23 then you should have to set permission at the run time ! or else try this
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/mysongs.mp3");
if(myFile.exists()){
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}

Related

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,
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.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

Android check if file exists() not work

I'm checking if the database in a folder of the device exists. The folder and the database exists, but is not found. The path is right, then where am I wrong?
private void checkDBexists() {
File internal = Environment.getExternalStorageDirectory();
File myFile = new File(internal.getAbsoluteFile() + "MyFolder/database.db");
if (myFile.exists()) {
importaDB();
} else {
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "not work", Toast.LENGTH_SHORT);
toast.show();
}
}
File myFile = new File(internal.getAbsoluteFile()+"/MyFolder/database.db");
Add "/" before MyFolder.

Reading file from SD card and loading it to WebView

i am trying to load a html file in webView from sd card its not working, Directory exists in SD card as well as file in it. Here is the code i have tried.
public void CheckReg()
{
File file = new File(getExternalCacheDir(), "Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///sdcard/Reginfo/input/register.html");
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
do this
File file = new File(Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
if (file.exists())
{
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
dont forget to
add permissions to menifest
should set like ,
public void CheckReg()
{
File file = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()+"Reginfo/input/register.html" );
if (file.exists())
{
index.loadUrl("file:///"+file);
Toast.makeText(mContext, "File Exists", Toast.LENGTH_SHORT).show();
}
}
You shouldn't hard code the directory of the sdcard like that. Its typically at /mnt/sdcard/ but this is never assured instead of this you can write it like this.
and before you load the file from sd-card you make ensure that sd-card is mounted.
You can use the following:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d(TAG, "No SDCARD");
} else {
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Reginfo/input/register.html");
}

Downloads the same file twice?

Hi i've been looking through various parts of my code to try and find out whats happening but can't seem to figure it out. The following code is supposed to be downloading two files one called "clientraw" and one called "clientrawextra" but for some reason when i look in the directory there are 2 versions of each file "clientraw...1..." "clientrawextra...1..."
Therefore it seems like it's downloading the files multiple times and i have no idea why??
Thanks in advance!
distance dis = new distance();
dis.findURL(value);
String url = dis.findURL(value);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientraw.txt");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
/////////////////////////////////////////////////////
distance disextra = new distance();
disextra.findextra(value);
String urlextra = disextra.findextra(value);
DownloadManager.Request requestextra = new DownloadManager.Request(Uri.parse(urlextra));
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
requestextra.allowScanningByMediaScanner();
}
requestextra.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientrawextra.txt");
manager.enqueue(requestextra);
mDownload = new DownLoadComplte();
registerReceiver(mDownload, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
And the broadcast receiver...
private class DownLoadComplte extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent myIntent = new Intent(splash.this, MainActivity.class);
myIntent.putExtra("key", value); //Optional parameters
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//unregisterReceiver(mDownload);
splash.this.startActivity(myIntent);
}
}
}
So if anyone has the same issue, apparently this is an ongoing and as of yet unresolved issue with the Download manager. I have used a little bit of a work around which you might want to use if your flow is similar to mine. Basically every time that the user opens the app two files are automatically downloaded to the SD card which overwrites the two files previously downloaded. So all i did was add a couple of extra functions to delete the duplicates...
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() +
"/Download/", client);
Log.d("file path", String.valueOf(file));
if(file.exists())
{
boolean flag = file.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra = Environment.getExternalStorageDirectory();
File fileextra = new File(sdCardextra.getAbsolutePath() +
"/Download/", clientextra);
boolean exist = fileextra.exists();
Log.d("the file exists = ", String.valueOf(exist));
if(fileextra.exists())
{
boolean flag = fileextra.delete();
Log.d("file", "file deleted " + flag);
}
File sdCard2 = Environment.getExternalStorageDirectory();
File file2 = new File(sdCard2.getAbsolutePath() +
"/Download/", "clientraw-1.txt");
Log.d("file path", String.valueOf(file2));
if(file2.exists())
{
boolean flag = file2.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra3 = Environment.getExternalStorageDirectory();
File fileextra3 = new File(sdCardextra3.getAbsolutePath() +
"/Download/", "clientrawextra-1.txt");
boolean exists = fileextra3.exists();
Log.d("the file exists = ", String.valueOf(exists));
if(fileextra3.exists())
{
boolean flag = fileextra3.delete();
Log.d("file", "file deleted " + flag);
}

how to check if file is available in internal storage

I am trying to download a file from the internet and it succeeded but now
I want to check if the file exists in the internal storage.
else if (arg0.getId() == R.id.btn_download)
{
Toast.makeText(this, "download button clicked", Toast.LENGTH_SHORT).show();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(names[b]));
request.setDescription("Downloading..");
request.setTitle("Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex() +1) );
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex()
+1) +".pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
The items retrieved are downloaded to /mnt/sdcard/Download.
How do I check if the file exists or not using code?
Let's say following is your file's path
String path=context.getFilesDir().getAbsolutePath()+"/filename";
File file = new File ( path );
if ( file.exists() )
{
// Toast File is exists
}
else
{
// Toast File is not exists
}
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+<file-name>);
if(applictionFile != null && applictionFile.exists()){
}
if file is getting downloads in to default donwload directory

Categories

Resources