Updating Progress Dialog in Activity from Asynctask

Updating progress dialog in Activity from AsyncTask

AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().

Refer to the docs for more details

Updating progress on progress dialog from AsyncTask can't build

 private class DownloadFile extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
String fileName=null;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create ProgressBar
mProgressDialog = new ProgressDialog(Task.this);
// Set your ProgressBar Title
mProgressDialog.setTitle("Downloads");
mProgressDialog.setIcon(R.drawable.dwnload);
// Set your ProgressBar Message
mProgressDialog.setMessage("Updating App Version, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Show ProgressBar
mProgressDialog.setCancelable(false);
// mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}

@Override
protected String doInBackground(String... sUrl) {
try {
String apkurl = "http://google.com/"+fileName;
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url
.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int fileLength = c.getContentLength();

//File file = new File(PATH);
if(file.exists())
{
file.delete();
}
file.mkdirs();
File outputFile = new File(file, fileName);
final FileOutputStream fos = new FileOutputStream(outputFile);

final InputStream is = c.getInputStream();

byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = is.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int) (total * 100 / fileLength));
fos.write(data, 0, count);
}

// Close connection
fos.flush();
fos.close();
is.close();
}
}

catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
}

@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Update the ProgressBar
mProgressDialog.setProgress(progress[0]);
}
}

Android : AsyncTask, how can update ProgressDialog increment

Try something like this,

Create a ProgressDialog.

ProgressDialog mProgressDialog = new ProgressDialog(Your_Activity.this);
mProgressDialog.setMessage("Here you can set a message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
MyAsyncTask obj = new MyAsyncTask ();
obj.execute("url");

Your AsyncTask Class.

private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int length = connection.getContentLength();

// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.txt");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/length));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
@Override
public void onProgressUpdate(String... args){
mProgressDialog.setProgress(args[0]);
}
}
}

You have to give these Permission's in the AndroidManifest file.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android - Can't update the activity ProgressDialog from custom AsyncTask class

Dont pass progress dialog to the Async class. Instead create it on the Async class.

Modify onPreExecute to this

@Override
public void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(getActivity(),"","Connexion au serveur distant...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

Delete progress dialog from test1.java

Android show a progress dialog before asyncTask

This should be the definitive answer, at least for my situation.

Easy to implement, works even if you're calling asyncTasks, etc.

how to update UI by using progressdialog from several instances of asynctask

Run AsyncTask successively, one by one, and update your dialog on preExecute or postExecute. And write your for loop in doInBackground, where i is a indicator what task executed.

ProgressDialog in AsyncTask

Fixed by moving the view modifiers to onPostExecute so the fixed code is :

public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;

//private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.sorties);

tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");

new ProgressTask(Soirees.this).execute();

}

private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}

/** progress dialog to show user that the backup is processing. */

/** application context. */
private Context context;

protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}

@Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();

if (dialog.isShowing()) {
dialog.dismiss();
}

if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}

protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();

return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}

}

}

@Vladimir, thx your code was very helpful.

How to use AsyncTask to show a ProgressDialog while doing background work in Android?

Place your ProgressDialog in onPreExecute, sample code below:

private ProgressDialog pdia;

@Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}

@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}

and in your onClickListener, just put this line inside:

new EfetuaLogin().execute(null, null , null);

External AsyncTask class with ProgressDialog [Update: and returning back?]

You were creating the ProgressDialog with a null context. The following code worked for me.

public class AsyncClass extends AsyncTask<Void, String, Void> {
private Context context;
ProgressDialog dialog;

public AsyncClass(Context cxt) {
context = cxt;
dialog = new ProgressDialog(context);
}

@Override
protected void onPreExecute() {
dialog.setTitle("Please wait");
dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(2000);
return (null);
}

@Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}


Related Topics



Leave a reply



Submit