Delete file if AsyncTask Fail - android

Currently
I am downloading a file from a URL, I'm doing this within AsyncTask inside a Adapter. The problem I have is that when I press back onBackPressed the download stops but the file remains in the folder FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/file.mp4");
My Question
Is it possible to delete the file if AsyncTask does not complete?
I have tried to do file.delete(); in the catch of doinbackground but I get error file.delete(); is ignored
Here is a summary of my adapter----
When Item in holder is clicked I call AsyncTask:
holder.setItemClickListener(new ItemClickListener() {
if (pos == 1) {
if(manager.fetchVideoPath(pos)==null) {
DownloadFileFromURL p = new DownloadFileFromURL();
p.execute(pos + "", "https://www.dropbox.com/s/xnzw753f13k68z4/Piper%20First%20Look%20%282016%29%20-%20Pixar%20Animated%20Short%20HD.mp4?dl=1");
a = "one";
bars.set(pos,new ProgressModel(pos,1));
//This is what is causing the issue
RecyclerVideoAdapter.this.notifyItemChanged(pos);
}
My AsyncTask:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(1);
}
#Override
protected String doInBackground(String... f_url) {
int count;
String pathreference = f_url[0]+",";
positionnumber = Integer.parseInt(f_url[0]);
try {
URL url = new URL(f_url[1]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
if (a.equals("one")) {
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/file.mp4");
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();
pathreference = pathreference+Environment.getExternalStorageDirectory().toString()+"/file.mp4";
output.close();
input.close();
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathreference;
}
protected void onProgressUpdate(String... progress) {
bars.get(positionnumber).setProgress_(Float.parseFloat(progress[0]));
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(bars.get(positionnumber).getProgress_());
}
#Override
protected void onPostExecute(String file_url) {
String []split = file_url.split(",");
int index1 = Integer.parseInt(split[0]);
videoHolderClass.set(index1,new VideoHolderClass(index1,imgres[0]));
bars.get(index1).setProgress_(0);
manager.insertVideoPath(index1+"",split[1]);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
}
}

Building on the answer on this post, try to put the logic of deleting the file inside isCancelled() like this:
if (isCancelled() && file.exists())
file.delete();
else
{
// do your work here
}
Then you can call p.cancel(true) inside onBackPressed

Related

Download Multiple Files Using Async

I am trying to download multiple files using asyc but for some reason it only downloads one file successfully while all the other files are 0 bytes.
Only the file that is added first to the string array is downloaded successfully, the rest are written as 0 bytes on the SD card.
class DownloadFileFromFTP extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
//code
//Read SharedPref
String str_dirRestoredImage_open = sharedPref.getString("SharedPref_dirRestoredImage_open", "");
int count;
OutputStream output = null;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
int totalFilesChecked = arrListStr_Files_Checked.size();
for (int i=0;i<totalFilesChecked;i++)
{
// Output stream
file_name_remote_abs = stringArr_Files_Checked[i];
file_name_remote = file_name_remote_abs.substring(file_name_remote_abs.lastIndexOf('/') + 1);
output = new FileOutputStream(str_dirRestoredImage_open+"/"+file_name_remote);
Log.d("LOG", "zzz_i: "+i +" :"+file_name_remote);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Stuff that updates the UI
Toast.makeText(getApplicationContext(), "File Restored: "+file_name_remote, Toast.LENGTH_LONG).show();
}
});
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
// Stuff that updates the UI
Toast.makeText(getApplicationContext(), "Failed To Restore: "+file_name_remote, Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
//pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(progress_bar_type);
}
}
This is how I am calling it, where stringArr_Files_Checked is a string array of absolute URLs of files.
new DownloadFileFromFTP().execute(stringArr_Files_Checked);

android :: show progress dialog till asynctask does not get complete

I am downloading a zip file of 15 mb and then unzip it in the sd card.
I am using progress dialog to show the status. First time it works perfectly, and when I change the db version number on server to download new file and start the app again then progress dialog disappears in between and causes crash in the app.
Below is the code.
class CheckInAppUpdatesAsyncTask extends AsyncTask<Void, Void, Void> {
Dialog progress;
#Override
protected Void doInBackground(Void... params) {
try {
downloadDB();
} catch (Exception e) {
}
}
#Override
protected void onPostExecute(final Void result) {
stopWorking();
}
#Override
protected void onPreExecute() {
startWorking();
}
};5
private void startWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
this.pDiag = ProgressDialog.show(Browse.context, "Working...",
"Please wait while we load the encyclopedia.", true, false);
}
}
private void stopWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
}
}
Download code
URL url = new URL(serverFileURL);
Log.d("FILE_URLLINK", "serverFileURL " + serverFileURL);
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
connection.getContentLength();
byte data[] = new byte[1024];
input = new GZIPInputStream(input);
InputSource is = new InputSource(input);
InputStream in = new BufferedInputStream(is.getByteStream());
String inAppDBName = Constants.NEW_DB_NAME_TO_DOWNLOAD;
OutputStream output = new BufferedOutputStream(new FileOutputStream(dir + "/" + inAppDBName));
int length;
while ((length = in.read(data)) > 0) {
output.write(data, 0, length);
}
output.flush();
output.close();
input.close();
Any idea?
You should put unzip code before stopWorking(); in onPostExecute.
It will not close till all things happen.

Maintain progress of progressbar on orientation change in android

I am trying to download multiple videos from server using AsyncTask, I have list of progress bar for videos but I am unable to maintain the progress for each progress bar on orientation change of my phone.
I am calling downlodThreadVideos() in adapter of listview
public UserVideoDTO downlodThreadVideos(final ProgressBar _progress, ImageView _imgLaunch, ImageView _imgDownload, UserVideoDTO vpideoDTO)
{
DownloadVideoFileAsyncTask mDownloadFileAsync = new DownloadVideoFileAsyncTask(videoDTO,_progress,_imgLaunch,_imgDownload);
mDownloadFileAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,videoDTO);
return mDownloadFileAsync._videoDTO;
}
private class DownloadVideoFileAsyncTask extends AsyncTask<UserVideoDTO, Integer, UserVideoDTO> {
ProgressBar _progress;
ImageView _imgLaunch;
ImageView _imgDownload;
public UserVideoDTO _videoDTO;
String OfflinePath=null;
public DownloadVideoFileAsyncTask(UserVideoDTO videoDTO,ProgressBar progress, ImageView imgLaunch, ImageView imgDownload) {
// TODO Auto-generated constructor stub
_videoDTO=videoDTO;
_progress = progress;
_imgLaunch=imgLaunch;
_imgDownload=imgDownload;
}
protected UserVideoDTO doInBackground(UserVideoDTO... params) {
UserVideoDTO videoDTO = _videoDTO;
try {
String _videoURL="http://mylinkforvideodownload/videoDTO.onlinepath";
if (cancelThread)
return null;
String Path = new String(_videoURL);
Path = Path.replaceAll(" ", "%20");
URL url = new URL(Path);
long startTime = System.currentTimeMillis();
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setConnectTimeout(60000);
File folder = new File(getExternalFilesDir(null).getAbsolutePath()+"/Download");
folder.mkdir();
String fileName = getExternalFilesDir(null).getAbsolutePath()+ "/Download/videos_";
File file = new File(fileName);
String offlineFileName = videoDTO.lmsvideoid;
String offlineFilePath = file + offlineFileName + ".mp4";
BufferedInputStream inStream = new BufferedInputStream(ucon.getInputStream());
FileOutputStream outStream = new FileOutputStream(offlineFilePath);
byte[] buff = new byte[1024];
int lengthOfFile = ucon.getContentLength();
int len;
long total = 0;
try {
while (!cancelThread && ((len = inStream.read(buff)) != -1)) {
total += len;
publishProgress((int) ((total * 100) / lengthOfFile));
outStream.write(buff, 0, len);
}
} catch (Exception e) {
cancelThread = true;
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
return videoDTO;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("ANDRO_ASYNC", progress[0].toString());
_progress.setProgress(progress[0]);
}
protected void onPreExecute() {
super.onPreExecute();
_progress.setMax(100);
}
protected void onPostExecute(UserVideoDTO result) {
super.onPostExecute(result);
_progress.setProgress(100);
}
protected void onCancelled() {
super.onCancelled();
}
}

how send a parametr from a method to another android

hi i have a DownloadFileAsync class for download file from url
i download file perfect from web but when download complete i want to play mp3 file from system but i cant send address file from doInBackground to onPostExecute
my code is :
protected String doInBackground(String... aurl) {
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(aurl[0]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
File myFolder = new File( root + "/download/"+aurl[1]+"/" );
myFolder.mkdir();
FileOutputStream f = new FileOutputStream(new File(root + "/download/"+aurl[1]+"/", aurl[2]+".mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[512];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
and onPostExecute code is :
protected void onPostExecute(String unused) {
mProgressDialog.dismiss();
File musicFile2Play = new File("/sdcard/download/بابالنگ دراز/شماره یک.mp3");
Intent i2 = new Intent();
i2.setAction(android.content.Intent.ACTION_VIEW);
i2.setDataAndType(Uri.fromFile(musicFile2Play), "audio/mp3");
context.startActivity(i2);
// intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "hamrahtest.apk")), "application/vnd.android.package-archive");
}
how send aurl[1] and aurl[2] from doInBackground to onPostExecute file name ?
You should fill your return from your doInBackground with the objects you wish your OnPostExecute need. For example:
protected List<String> doInBackground(String... aurl) {
List<String> list = new ArrayList<String>();
try {
File root = Environment.getExternalStorageDirectory();
...
list.add(aurl[0]);
list.add(aurl[1]);
list.add(aurl[2]);
list.add(aurl[3]);
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return list;
}
protected void onPostExecute(List<String> list) {
mProgressDialog.dismiss();
for (String url : list) {
// Do you handling here
}
}
You should declare your AsyncTask like this:
public class MyAsyncTask extends AsyncTask<Void, Void, List<String>> {
First:
DownloadFileAsync extends AsyncTask<String, String, String[]>
Second change
protected String doInBackground(String... aurl) {
to
protected String[] doInBackground(String... aurl) {
.....
......
return aurl;
}
Third change
protected void onPostExecute(String unused)
to
protected void onPostExecute(String[] aurl) {
A simple solution would be to make these instance variables on your AsyncTask class. Set them in doInBackgroound, read them in onPostExecute().

how to download file in android download service

i have this url http://translate.google.com/translate_tts?ie=UTF-8&q=hi&tl=en&total=1&idx=0&textlen=2
when i place it to pc and android browser it makes me force to download
how can i make it download in my android application without browser.
i tried to make to download using this tutorial how can i download audio file from server by url
.but it did not work.
anyone please help
Thank you Kristijana Draca think it is working but where it save in emulator here is my code public class Main extends Activity {
EditText inputtext;
Button listen;
Button shareButton;
TextView tv;
ProgressBar proBar;
//ProgressDialog progress;
MediaPlayer player;
public Boolean isPlaying=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadContent();
}
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://translate.google.com/translate_a/t?client=t&source=baf&sl=ar&tl=en&hl=en&q=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&sc=1 ");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ "com.jony.com" + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
}
});
You can download any file using AsyncTask.
downloadContent();
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://somehost.com/file.mp3");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ PACKAGE_NAME + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}

Categories

Resources