I am trying to download a file with asyncTask but is not working, there is no error messages or nothing, just dont download the file... i try everything but it appears that is not entering on the while... anybody know what can be the problem? I tested on my mobile, the url is ok too.
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
I just ran your code, and it works fine for me. The image was downloaded to the sdcard.
Just to note, make sure you have these permissions set in your AndroidManifest.xml:
Here are the logs I got (note that I added a
ProgressDialog
):Just in case this will be useful, here is the full MainActivity.java code that worked for me. (url is a placeholder):