Maintain progress of progressbar on orientation change in android - 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();
}
}

Related

Delete file if AsyncTask Fail

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

Image not downloading from Async Task

I am trying to download image on button click through Async Task but the image is not downloading. Is there any problem with the download link in the String "image_url"?
Logcat - skia: --- SkImageDecoder::Factory returned null
public class DownloadImageAsyncTask extends AppCompatActivity {
Button button;
ImageView imageView;
String image_url = "http://www.freegreatdesign.com/files/images/6/2921-large-apple-icon-png-1.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image_async_task);
button = (Button) findViewById(R.id.bDownload);
imageView = (ImageView) findViewById(R.id.downImage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(image_url);
}
});
}
class DownloadTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(DownloadImageAsyncTask.this);
progressDialog.setTitle("Download in progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String path = params[0];
int file_length = 0;
try {
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length = urlConnection.getContentLength();
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists())
{
new_folder.mkdir();
}
File input_file = new File(new_folder, "downloaded_image.jpg");
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
byte[] data = new byte[1024];
int total = 0;
int count = 0;
OutputStream outputStream = new FileOutputStream(input_file);
while((count=inputStream.read())!=-1)
{
total+=count;
outputStream.write(data, 0, count);
int progress = (int) total*100/file_length;
publishProgress(progress);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Download Complete...";
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(String result) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
String path = "sdcard/photoalbum/downloaded_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
}

Ekito Simple KML read source

I have one KML at this link:
http://myurl.com/mykml.kml
I want to get the com.ekito.simpleKML.model KML object from it.
I'm trying with this:
String url = "http://myurl.com/mykml.kml";
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
But the kml object is still null.
This is the link to the Ekito Simple KML library: https://github.com/Ekito/Simple-KML
I see the Ekito he can not read a file on the internet. Test this example!
private ProgressDialog progressBar;
public static final int KML_PROGRESS = 0;
public String fileURL ="http://myurl.com/mykml.kml";
// set in OnClick Button
new DownloadKML().execute(fileURL);
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case KML_PROGRESS:
progressBar = new ProgressDialog(this);
progressBar.setMessage("Downloading fileā€¦");
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setCancelable(true);
progressBar.show();
return progressBar;
default:
return null;
}
}
class DownloadKML extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(KML_PROGRESS);
}
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL( url[0] );
URLConnection connect = url.openConnection();
connect.connect();
int progressOfFile = connect.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/KML_Samples.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/progressOfFile) );
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
String pathKML = Environment.getExternalStorageDirectory().toString() + "/KML_Samples.kml";
// load
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
}
}

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);
}
}

Download in android large files

When I try this code, it starts download but then stuck with alert "force close"
what should I do? Use some kind of background thread?
try {
long startTime = System.currentTimeMillis();
URL u = new URL("http://file.podfm.ru/3/33/332/3322/mp3/24785.mp3");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("/sdcard/","logo.mp3"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 ) {
f.write(buffer,0, len1);
}
f.close();
Log.d("ImageManager", "download ready in" +
((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
catch (IOException e)
{
Log.d("ImageManager", "Error" +
((System.currentTimeMillis()) / 1000) + e + " sec");
}
I was dealing with similar problem last week and ended up using AsyncTask with progress bar displayed since it could take some time for the file to be downloaded. One way of doing it is to have below class nested in your Activity and just call it where you need to simply like this:
new DownloadManager().execute("here be URL", "here be filename");
Or if the class is not located within an activity and calling from an activity..
new DownloadManager(this).execute("URL", "filename");
This passes the activity so we have access to method getSystemService();
Here is the actual code doing all the dirty work. You will probably have to modify it for your needs.
private class DownloadManager extends AsyncTask<String, Integer, Drawable>
{
private Drawable d;
private HttpURLConnection conn;
private InputStream stream; //to read
private ByteArrayOutputStream out; //to write
private Context mCtx;
private double fileSize;
private double downloaded; // number of bytes downloaded
private int status = DOWNLOADING; //status of current process
private ProgressDialog progressDialog;
private static final int MAX_BUFFER_SIZE = 1024; //1kb
private static final int DOWNLOADING = 0;
private static final int COMPLETE = 1;
public DownloadManager(Context ctx)
{
d = null;
conn = null;
fileSize = 0;
downloaded = 0;
status = DOWNLOADING;
mCtx = ctx;
}
public boolean isOnline()
{
try
{
ConnectivityManager cm = (ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
catch (Exception e)
{
return false;
}
}
#Override
protected Drawable doInBackground(String... url)
{
try
{
String filename = url[1];
if (isOnline())
{
conn = (HttpURLConnection) new URL(url[0]).openConnection();
fileSize = conn.getContentLength();
out = new ByteArrayOutputStream((int)fileSize);
conn.connect();
stream = conn.getInputStream();
// loop with step
while (status == DOWNLOADING)
{
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE)
{
buffer = new byte[MAX_BUFFER_SIZE];
}
else
{
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1)
{
publishProgress(100);
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
// update progress bar
publishProgress((int) ((downloaded / fileSize) * 100));
} // end of while
if (status == DOWNLOADING)
{
status = COMPLETE;
}
try
{
FileOutputStream fos = new FileOutputStream(filename);
fos.write(out.toByteArray());
fos.close();
}
catch ( IOException e )
{
e.printStackTrace();
return null;
}
d = Drawable.createFromStream((InputStream) new ByteArrayInputStream(out.toByteArray()), "filename");
return d;
} // end of if isOnline
else
{
return null;
}
}
catch (Exception e)
{
e.printStackTrace();
return null;
}// end of catch
} // end of class DownloadManager()
#Override
protected void onProgressUpdate(Integer... changed)
{
progressDialog.setProgress(changed[0]);
}
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(/*ShowContent.this*/); // your activity
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Downloading ...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Drawable result)
{
progressDialog.dismiss();
// do something
}
}
You should try using an AsyncTask. You are getting the force quit dialog because you are trying to do too much work on the UI thread and Android judges that your application has become unresponsive.
The answers to this question have some good links.
Something like the following would be a good start:
private class DownloadLargeFileTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog;
public DownloadLargeFileTask(ProgressDialog dialog) {
this.dialog = dialog;
}
protected void onPreExecute() {
dialog.show();
}
protected void doInBackground(Void... unused) {
downloadLargeFile();
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
and then execute the task with:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading. Please Wait...");
new DownloadLargeFileTask(dialog).execute();

Categories

Resources