Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.
By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}
im building an android App that download books in pdf format from url and storage it into the device , so i wrote this code to make folder named " Mypdf " and save the file after it download in it , but when i run the app in the device i only found Mypdf file but there is no any pdf book , below the code i used
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf");
file.mkdir();
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("Mypdf/ "+booknameText+ ".pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(getApplicationContext(), "The Book You downloaded had been saved into your SD Card " , Toast.LENGTH_LONG).show();
}
}
}
i used this function :
OutputStream output = new FileOutputStream("/sdcard/ "+booknameText+ ".pdf");
but some times many device's do'not have sdcard so the file will not be saved , so please can you help guys
I have an android app which downloads a video by clicking a button and saves it on user's device. when users click on the button the app checks if the video is in users' device, and if it is not it downloads the video and if it has been downloaded the app just plays the video without the need to download.
However when the download crashes the file is there , but the app can't plays it and gets tricked that the file has been downloaded already.
I wanted to ask if there are any ways to check if the download process has crashed or the file is corrupted.
Thanks
You can use AsyncTask as below to check if the download was interupted or not.
Below code is just for example purpose
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
initialText.setText(getString(R.string.connecting));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String fileURL = f_url[0];
if (fileURL.contains(" ")) {
fileURL = fileURL.replace(" ", "%20");
}
URL url = new URL(fileURL);
filename = f_url[0].substring(fileURL.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File file = new File(FilePath);
if (!file.exists()) {
if (!file.isDirectory()) {
file.mkdirs();
}
}
// Output stream to write file
OutputStream output = new FileOutputStream(FilePath + filename);
byte data[] = new byte[1024];
long total = 0;
runOnUiThread(new Runnable() {
#Override
public void run() {
setSubTitle(getString(R.string.downloading));
initialText.setText(ad_tv_initialText.getText().toString() + getString(R.string.connected));
}
});
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "SUCCESS";
} catch (Exception e) {
return "FAILED";
}
}
protected void onProgressUpdate(String... progress) {
progress.setProgress(Integer.parseInt(progress[0]));
progressText.setText(progress[0] + " %");
}
#Override
protected void onPostExecute(String result) {
if (result.equals("SUCCESS")) {
takeDecisionToPlay();
} else if (result.equals("FAILED")) {
setSubTitle(getString(R.string.failed_));
finalText.setText(getString(R.string.failed));
}
}
}
am using sound cloud search api. when i hit the search url it give me search results. every audio has stream url but not download url because it depends on setting of the uploader. Every none downloadable file also has download count more than 1. for example, when you'll hit this url
http://api.soundcloud.com/tracks.json?client_id=4346c8125f4f5c40ad666bacd8e96498&q=tere%20bin&limit=1
It'll give the search result like that
[{"kind":"track","id":63225776,"created_at":"2012/10/13 01:52:38 +0000","user_id":26029726,"duration":206177,"commentable":true,"state":"finished","original_content_size":3298521,"last_modified":"2014/10/01 18:56:25 +0000","sharing":"public","tag_list":"","permalink":"tere-bin-uzair-jaswal-official","streamable":true,"embeddable_by":"all","downloadable":false,"purchase_url":null,"label_id":null,"purchase_title":null,"genre":"Musical","title":"Tere Bin - Uzair Jaswal [Official Music Audio]","description":"","label_name":"","release":"","track_type":"original","key_signature":"","isrc":"","video_url":null,"bpm":null,"release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/63225776","user":{"id":26029726,"kind":"user","permalink":"uzair-jaswal-1","username":"Uzair Jaswal Music","last_modified":"2014/10/19 13:06:28 +0000","uri":"https://api.soundcloud.com/users/26029726","permalink_url":"http://soundcloud.com/uzair-jaswal-1","avatar_url":"https://i1.sndcdn.com/avatars-000110064166-2ts508-large.jpg"},"permalink_url":"http://soundcloud.com/uzair-jaswal-1/tere-bin-uzair-jaswal-official","artwork_url":"https://i1.sndcdn.com/artworks-000032079002-kup6vc-large.jpg","waveform_url":"https://w1.sndcdn.com/9bwAsZfGrxwN_m.png","stream_url":"https://api.soundcloud.com/tracks/63225776/stream","playback_count":359588,"download_count":100,"favoritings_count":7557,"comment_count":491,"attachments_uri":"https://api.soundcloud.com/tracks/63225776/attachments","policy":"ALLOW"}]
this is for only one audio and that audio is not downloadable but it has download count of 100. how is this possible ?
can anybody tell me how i can download that audio which is not downloadable?
any help would be much appreciated. Thanks :)
I fix it myself, i was using android and the stream url is also a download url. the stream url is also download url for downloading but it won't affect on download count. you can try like that
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
pass this url to asyntack and manage you download there, you can pass it like that
new DownloadFileFromURL().execute(file_url);
here is DownloadFileFromUR class using asyntask
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
URL u = null;
InputStream is = null;
try {
u = new URL(f_url[0]);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection();//to know the size of video
int size = huc.getContentLength();
if(huc != null){
String fileName = "FILE2.mp3";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
long total = 0;
int len1 = 0;
if(is != null){
while ((len1 = is.read(buffer)) > 0) {
total+=len1;
publishProgress((int)((total*100)/size));
fos.write(buffer,0, len1);
}
}
if(fos != null){
fos.close();
}
}
}catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null){
is.close();
}
}catch (IOException ioe) {
// just going to ignore this one
}
}
return "";
}
#Override
protected void onPostExecute(String file_url) {
}
}
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
DownLoad Class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(file_url);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(getOutputMediaFile());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
Hi everyone I'm trying download file from url if exist… my problem is file downloaded without exist from server…
i will appreciate if anyone help me…
I can not figure out check if file exist download it if not ignore…
private void startDownload() {
// TODO Auto-generated method stub
String url = "http://example.com/file/krs.db";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
// create empty directory if not exist
File appDir = new File(sdcardBaseDir + externalPath);
if (!appDir.exists())
appDir.mkdirs();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(sdcardBaseDir
+ externalPath + IcsvFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
}
}
Appreciate your help..
Use the code below to check whether your file is exist in the given url.
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
The method returns 'true' if file exists, Then download it.
Ignore otherwise.
If you connect to a HTTP URL, you will actually get back a HttpURLConnection object. It has a getResponseCode method that gives you the HTTP status code.