I’m trying to download a file from within my application. I’ve set a button’s onClickListener to call this method:
private void downloadFile(String fileUrl, File destDir, String fileName) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdirs();
}
FileOutputStream output = new FileOutputStream(new File(destDir.toString() + "/" + fileName));
InputStream input = connection.getInputStream();
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = input.read(buffer)) != -1) {
output.write(buffer, 0, byteCount);
}
output.close();
input.close();
} catch (IOException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("IOException", "Error: " + e.getMessage(), e);
} finally {
Toast.makeText(this, "File downloaded: " + fileName, Toast.LENGTH_SHORT).show();
}
}
I’ve been going through various topics, but neither one seemed to come up with a usable solution. When I use the code specified above, nothing seems to happen.
EDIT: The file will download in the background and show a short toast when finished. The button seems to be “clicked” while downloading, though. Any thoughts on this?
Thanks for your help!
Actually I didn’t need all that code. I just had to use something similar to this:
private void getFile(String url) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
This should also be useful to some people:
private void openFile(File file) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
If nothing happens, you should add some logging to your code.
And you could also show the error to the user, by calling
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show()Better would be to show the root cause message using helper methods like these: