how to show progress when read any URL in android? - android

I have one problem in url like"http://sample.com/test" that have large amout of xml data i am not able to show progress bar in mainUI.
Please do needful.

In AsyncTask ,background task save the xml in local memory.
int count;
try {
URL url = new URL("http://sample.com/test");
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("/data/data/com.pc.demo/temp.xml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progress = (int)((total*100)/lenghtOfFile) ;
System.out.println("update---"+progress);
publishProgress(progress);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
onPostExecute
File yourFile = new File("/data/data/com.pc.demo/temp.xml");
InputStream input = new BufferedInputStream(new FileInputStream(yourFile), 8086);
onProgressUpdate
setProgressPercent(progress[0])

you can override the onProgressUpdate() function of your AsyncTask, and use the publishProgress(Progress... values) in the doInBackgroud() to push your saving status to the progress then update it, here is my simple code, wish can help you.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]); //change this with your progress bar
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}

Related

Android Asynctask get last progress in background after destroy activity

What I want to do now is loop download pdf from URL that has about 875 Files.
I have already done this by using Asynctask and update the progress in progress dialog also everything is working fine, but what I had a problem is when the user clicks on my DOWNLOAD IN BACKGROUND button, the download is still going on and then I want to re-open the activity again. but the progress and name of the file that displays to the user is not showing anymore.
I know that when we start new activity it will ignore the background running process of our last Asynctask, so how could we solve this problem? (sorry for my English, it's my first time through on StackOverflow)
my code is similar to this
Here sample of my code:
class DownloadFileFromURL extends AsyncTask<ArrayList<LawDocument>,Integer, String> {
private boolean running = true;
Exception error;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(haveNetworkConnection()){
showDialog(progress_bar_type);
}else {
running = false;
showdailog();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
running = false;
}
#Override
protected String doInBackground(ArrayList<LawDocument>[] f_url) {
ArrayList<LawDocument> passed = f_url[0]; //get passed arraylist
System.out.println("Data::" + passed.size());
int count;
InputStream input = null;
OutputStream output = null;
while(!isCancelled()) {
try {
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.setMessage(countfile+" / "+ConstantClass.filecount);
}
});
}
}
} catch (Throwable t) {
Log.e("AsyncTask", "OMGCrash", t);
// maybe throw it again
Toast.makeText(DownloadLoading.this,"There is a problem",Toast.LENGTH_SHORT).show();
throw new RuntimeException(t);
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(Integer... progress) {
// setting progress percentage
pDialog.setProgress(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);
if (error !=null){
Toast.makeText(DownloadLoading.this, error.getMessage(),
Toast.LENGTH_SHORT).show();
}else if(!running){
Log.d("Faild","Download fail connection");
}else{
Toast.makeText(DownloadLoading.this, "Success", Toast.LENGTH_SHORT).show();
}
}
}
}
}
I guess the Best solution to you is using Service with BroadCast
which Mean but all your download In Service
lets say
public class DowloadService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
your_data = extras.get() // just example
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
// send broadcast with data you want
ntent.putExtra("dataType",dataType);
intent.putExtra("getAccuracy",gpsSignal);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
});
return START_NOT_STICKY;
}
}
and then in your activiy Setup Local BroadCast To get Data send
private class BroadCastLocal extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if (Constrains.PEDOMETERBROADCAST.equalsIgnoreCase(intent.getAction()))
{
int dataType = intent.getIntExtra("dataType",-1);
}
}
Now whenever the user start/end your activity .. the process will not be effected

ProgressDialog of AsyncTask

Hi I need to show summary progress of AsyncTask. I want to show ProgressBar or ProgressDialog of Downloading, but I have know idea what to do, I know how to show dialog, but only when I download one file, and how do when I have a lot of files to download. Can somebody help????
Here is My AyncTaskClass
public class DownloadProgramTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
String path = sUrl[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(path);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
And I create new instance of that class for every execute,
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK", MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
File imgLargeFile = new File(dirImageLarge, a.getId() + ".png");
if (!imgLargeFile.exists()) {
imgLargeList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + "/" + a.getImgLarge(), imgLargeFile.getPath());
}
you can use the overridden method OnProgressUpdate of Async Task. call publishProgress in doingBackground of asynctask with interger
something like this..
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("makemachine", "onProgressUpdate(): " +
percentBar.setProgress((values[0] * 2) + "%");
}

Download a file using asynctask and showing progressbar

i have a following code to download an image , show a progress bar and return its bitmap. but the bitmap always returns null.. once i remove the while loop, the bitmap has value, but i dont get a progress bar.
#Override
protected Bitmap doInBackground(String... params) {
bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = connection.getInputStream();
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
Log.e("could not load ", e.getMessage());
e.printStackTrace();
return null;
}
}
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
public void onPostExecute(Bitmap result) {
pDialog.dismiss();
listener.onTaskCompleted(result);
}
enter code here
an InputStream can only read one time. you need to change your code to :
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
String pathName=Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
you don't need interface because asynctask can return bitmap.
private class DownloadFilesTask extends AsyncTask<String, Integer, Bitmap> {
protected Bitmap doInBackground(String... params) {
return downloadBitmap();
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
When you call task you must use get();
Bitmap bitmap = new DownloadFileTask().execute().get();

Android updating progress doesn't work while downloading LARGE files

I have read this topic
and I have a problem about downloading large files, because progress dialog does not upload progress or upload only once after downloading and show 100% suddenly. But all works perfectly when I'm downloading small files.
I think problem may be here:
publishProgress((int)(total*100/fileLength));
My code:
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();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePat();
File dir = new File(sdpath + "/Myfolder");
dir.mkdir();
OutputStream output = new FileOutputStream(dir.toString() + "/" + "myfilename");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total/fileLength)*100);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
My file is about 80 mb.
You should try to divide first :
publishProgress((int)(total/fileLength)*100);
as you can get an out of range division.

How to get the time of download

I need to get the time of download when I launch my android application. So, I added 2 Log and System.currentTimeMillis(). But, I can’t find the exact location to put these tools.
To get the start time, I added this :
period=System.currentTimeMillis();
System.out.println("Début téléchargement : "+System.currentTimeMillis());
To ser the end time, I added this :
System.out.println("Fin téléchargement : "+System.currentTimeMillis());
period=(System.currentTimeMillis()-period);
System.out.println("La durée de téléchargement : "+period+"ms");
And this is all the code to download file :
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 vSDCard = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
vSDCard = Environment.getExternalStorageDirectory();
File vFile = new File(vSDCard.getParent() + "/" + vSDCard.getName() + "/"
+ "image.jpg");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(vFile);
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) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
ProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I need your suggestion please.
First block before open URL connection or just before you start reding from input stream.
Second block after close of connection or just after the loop.
What's so difficult about it? Am I missing something ?

Categories

Resources