I am developing an app that grabs a new json file every time is starts. But I've found that even though I delete the file and download the new one, the phone somehow still ends up with the old file.
Delete code:
if (test.exists()) {
test.delete();
Log.i(TAG, "Deleting File");
} else {
Log.i(TAG, "File does not exist");
}
Download Code:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(path));
request.setTitle("stations.json");
request.setDescription("File is being downloaded.....");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setDestinationInExternalFilesDir(getApplicationContext(), null, "stations.json");
request.setVisibleInDownloadsUi(false);
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
jsonRef = manager.enqueue(request);
I've deleted the file myself from the storage. It still grabs the old file. I've checked in a browser if the server version is updated. It was. I'm at a loss as to what may be happening. If the Stack community has any suggestions, it would be greatly appreciated. Thanks so much!
It appears that my phone was somehow caching the file. It would see that I was downloading the same file and would instead just give it to me. By giving it a new url, it tricked the app into thinking it was a new file.
In the end, what worked was to add:
?v=" + Math.random()
to the end of the file.
For Example:
String path = example.com/stations.json?v=" + Math.random();
Then download with:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(path));
Related
What I'm trying to achieve is to check before download if the file exists so i don't have to re-download it again. For example, i have to open for the first time this pdf from the Internet "history-of-comics.pdf", in order to do so i have to download it and open inside my app, the second time i choose to re-read it, i have to be sure that "history-of-comics.pdf" if exists inside Downloads/MyDocs, i don't have to waste resources and let the user wait to download it again. Currently the app targetSdkVersion is 29 and what i have done so far is:
Give permissions for READ_EXTERNAL_STORAGE & WRITE_EXTERNAL_STORAGE
Included in manifest android:requestLegacyExternalStorage="true" inside application tag
Download the pdf file in the MyDocs inside Downloads folder
Below is a quick sample of my code (i have commented the other combinations i have tried):
private void checkIfPdfExists(String pdfFileName) {
String uriFile = String.valueOf(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+File.separator+"MyDocs"+File.separator+pdfFileName+".pdf"));
File file = new File(uriFile);
//File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/MyDocs", pdfFileName+".pdf");
//File file = new File(Environment.DIRECTORY_DOWNLOADS+File.separatorChar+"MyDocs"+File.separatorChar+pdfFileName+".pdf");
//File file = new File(Environment.DIRECTORY_DOWNLOADS+File.separatorChar+"MyDocs", pdfFileName+".pdf");
if (file.exists() && file!=null) {
Toast.makeText(getApplicationContext(), file.getPath() + "/n exists", Toast.LENGTH_SHORT).show();
displayFromUri(Uri.parse(file.getPath()));
} else {
beginDownload("https://www.heritagestatic.com/comics/d/history-of-comics.pdf",pdfFileName);
}
}
And this is how i define the path when i download the pdf, the downloader works as it should:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.addRequestHeader("Accept", "application/pdf");
request.setDescription(file_name);
request.setTitle("Getting your doc");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"MyDocs/"+file_name+".pdf");
I did some research before posting the question and in some threads i found that is related to Android Q, but i can't find a real solution for it. Any help would be appreciated, thanks in advance!
The solution to my problem was how i was referring to file path and the method used for download. As #blackapps mentioned that if you use "setDestinationInExternalFilesDir" to save the file, the proper way to check if the file exist is with "getExternalFilesDir", in my case:
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+File.separator+"MyDocs"+File.separator+pdfFileName+".pdf");
I am using DownloadManager to download pdf file in my application. In devices with OS version of Oreo and above, the file is queued for download and keeps on downloading. But after some time nothing happens and no error or exception is shown. The same works fine in the device of OS version below Oreo.
Below is the code used.
private void startDownload(String downloadPath, String destinationPath) {
Uri uri = Uri.parse(downloadPath); // Path where you want to download file.
File destinationFile = new File(Environment.getExternalStorageDirectory() + "/folder_name");
destinationFile.mkdir();
destinationFile = new File(destinationFile.getAbsolutePath(), "file_name.pdf");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); // Tell on which network you want to download file.
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // This will show notification on top when downloading the file.
request.setTitle("Downloading a file"); // Title for notification.
request.setVisibleInDownloadsUi(true);
request.setDestinationUri(destinationFile); // Storage directory path
((DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request); // This will start downloading
}
Have enabled required permissions and tried setting Network type as well but no luck. Please help me with this.
Thanks in advance.
So my program works like this:
It downloads a .txt file from the dropbox and saves it to downloads directory.
Uri uri = Uri.parse(file);
DownloadManager.Request r = new DownloadManager.Request(uri);
// This put the download in the same Download dir the browser uses
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upload");
r.allowScanningByMediaScanner();
// Start download
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);
And the code is working fine, it downloads the file called upload.txt.
So now i want to read from it. I have been looking for some codes and nothing seems to be working...
Here is my current code, it throws a FileNotFoundException but file is located there.
Any tips?
String text="";
FileInputStream Fin=new FileInputStream(Environment.DIRECTORY_DOWNLOADS+"upload");
byte[] b=new byte[100];
Fin.read(b);
text=new String(b);
Fin.close();
Ofc i have tried putting "upload.txt", and even "/upload" and "/upload.txt" but still nothing.
If anyone can give me code that reads a text file, it would be awesome, or if someone could give me a code that can get the source code form a html site ( without JSOUP and other parsers, i have tried that, i want to implement my own parser ).
Thanks!!
Change
FileInputStream Fin=new FileInputStream(Environment.DIRECTORY_DOWNLOADS+"upload");
to
FileInputStream Fin=new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "upload"));
You should use Environment.getExternalStoragePublicDirectory to get the path.
Or if you like more,
FileInputStream Fin=new FileInputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/upload");
Change
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upload");
too with
r.setDestinationInExternalPublicDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "upload");
Took me ages, but finally:
You should add to the manifest the various permissions (android.permission.READ_EXTERNAL_STORAGE...)
But this is not enough!
you should explicitly ask for these permissions in the onCreate():
requestPermissions({android.permission.READ_EXTERNAL_STORAGE,...}, 200);
Only afterwards you can access these directories.
My app has 5 big text files on them, each one about 40kb. Those files are updated weekly on a website.
I managed to set downloadManager to download the 5 files from the site. The problem is that I don't want the user to be able to use the app while the files are downloading because that will cause problems.
I want that when the user clicks the "Update" button it will show up a loading box. Then when the files finish downloading the box will disappear and a toast will say "Updated."
This is the method I've set up:
#SuppressLint("NewApi")
public void DownloadTxtFile(String url, String fileName) {
if (!new File(Environment.getExternalStorageDirectory()
+ "/folder").exists()) {
new File(Environment.getExternalStorageDirectory()
+ "/Dovahzul_Dictionary").mkdirs();
}
File file = new File(extStore.getAbsolutePath()
+ "/folder/" + fileName);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDescription("Downloading Text Files...");
request.setTitle("Updating")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("/Dovahzul_Dictionary",
fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
if (file.exists()) {
file.delete();
} else {
}
manager.enqueue(request);
}
By the way, if you find any problem with the method, plase inform me as well.
Thanks in advance.
I know this is old, but to anyone that has the same problem: What you need to do, is start the download in a different thread.
As android is not thread prof, you need to use AsyncTask instead. An AsyncTask is very similar to a thread. By starting and using one, you can do some quite long operations without freezing the ui. (Note that AsyncTasks are recomended for operations that take seconds, not minutes. In that case, you need to find something else)
You start an AsyncTask, and make it download the file. The problem is that AsyncTasks can't access ui methods, so they can't change threads.
You can, luckly, override a method they have to update the ui, and call it directly from it's onExecute.
Many tutorials on this can be found in the web.
Hi have simple app in which data has been uploaded from the web server I am using .net web services. I need to replace the document on same location, so that duplicate document not place on same folder.
I am using:
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS + "/Downloads",
name );
is it right approach? can I delete document from physical place and then replace it with new one. if yes How this thing is possible.
this is my download manager and I am trying to delete name document and then trying to replace with new one. Please suggest. thanks
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// 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 + "/Downloads", name);
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);