Progressdialog in Asynctask

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 set progress dialog in AsyncTask

You should Override onPreExecute() method before doInBackground method.

ProgressDialog myPd_bar;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(title);
myPd_bar.show();
super.onPreExecute();
}

Then you should Override onPostExecute() method after doInBackground method.

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

You can find more information from this link

Android ProgressDialog in AsyncTask

You are trying to do a parseInt on a String containing "Loaded "+progress+"%". It can't work. Try this :

publishProgress(""+progress);

// [...]

protected void onProgressUpdate(String... progress)
{
Log.d("ANDRO_ASYNC", "Loaded " + progress[0] + "%");
pd.setProgress(Integer.parseInt(progress[0]));
}

How to use progress dialog in AsyncTask in android

no need to return current Activity instance from doInBackground because AsyncTask is inner class of Activity so you just use LoginActivity.this to start next Activity change your AsyncTask class as :

   private class log_in extends AsyncTask<String,Void,String>{
ProgressDialog pDialog;
@Override
protected void onPreExecute(){
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
login();
return null;
}
protected void onPostExecute(String params){
super.onPostExecute(params);
pDialog.dismiss();
if(userverified==true){
Intent intent=new Intent(LoginActivity.this,menu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
LoginActivity.this.startActivity(intent);
}
else{
error.setText("Wrong password or username combination");
}

}

}

because it's not possible to updating UI elements from doInBackground and you are trying to set textview text inside login() method instead of changing Textview text just make userverified==false

Progress Dialog not showing during a asynctask call

Call "super.onPreExecute();" and "super.onPostExecute(result);" after your code for progress dialog. Or better, get rid of them (if you don't have reasons for calling them).

Use the following code:

private class runningMan extends AsyncTask<Void, Void, Integer>
{

@Override
protected void onPreExecute() {

Log.d("Runningman: ", "Started running");
//this method will be running on UI thread
progress = ProgressDialog.show(PromotionMain.this, "Loading", "PleaseWait", true);
super.onPreExecute();

}
@Override
protected Integer doInBackground(Void... params) {
//parse the JSON string
JSONParser jp = new JSONParser();
try {
Log.d(username , password);
jp.parsesData(promos, myJson, pictureArray, pathArray, labelArray);
Log.d("Runningman: ", "Finished parsing");
} catch (IOException e) {
e.printStackTrace();
}

return 1;
}
@Override
protected void onPostExecute(Integer result) {
ArrayList<ListItem> listData = getListData();
fillListView(listData);
Log.d("Runningman: ", "Finished runing");
//this method will be running on UI thread
progress.dismiss();
super.onPostExecute(result);
}

}

How do I dismiss a progress dialog with async task and avoid is your activity running error?

Careful while handling views, activities and other related UI objects from another thread. Threads like AsyncTask are not aware of the activity lifecycle, and you may end up posting things to dead windows. I believe this is what is happening to you.

A safer way to do this:

import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.lang.ref.WeakReference;

public class MyTask extends AsyncTask<Void, Void, Void> {

private final WeakReference<MyActivity> weakReferenceActivity;

public MyTask(@NonNull MyActivity activity) {
this.weakReferenceActivity = new WeakReference<>(activity);
}

@Nullable
public MyActivity getActivity() {
MyActivity activity = weakReferenceActivity.get();
if (activity.isDestroyed()) {
return null;
}
return activity;
}

@Override
protected void onPreExecute() {
MyActivity activity = getActivity();
if (activity != null) {
activity.showProgressDialog();
}
}

@Override
protected Void doInBackground(Void... voids) {
[do something]
return null;
}

@Override
protected void onPostExecute(Void nothing) {
MyActivity activity = getActivity();
if (activity != null) {
activity.hide();
}
}
}

android how to work with asynctasks progressdialog

onProgressUpdate() is used to operate progress of asynchronous operations via this method. Note the param with datatype Integer. This corresponds to the second parameter in the class definition. This callback can be triggered from within the body of the doInBackground() method by calling publishProgress().

Example

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AsyncTaskExample extends Activity {

protected TextView _percentField;

protected Button _cancelButton;

protected InitTask _initTask;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_percentField = (TextView) findViewById(R.id.percent_field);
_cancelButton = (Button) findViewById(R.id.cancel_button);
_cancelButton.setOnClickListener(new CancelButtonListener());
_initTask = new InitTask();
_initTask.execute(this);
}

protected class CancelButtonListener implements View.OnClickListener {

public void onClick(View v) {
_initTask.cancel(true);
}
}

/**
* sub-class of AsyncTask
*/
protected class InitTask extends AsyncTask<Context, Integer, String> {

// -- run intensive processes here
// -- notice that the datatype of the first param in the class definition matches the param passed to this
// method
// -- and that the datatype of the last param in the class definition matches the return type of this method
@Override
protected String doInBackground(Context... params) {
// -- on every iteration
// -- runs a while loop that causes the thread to sleep for 50 milliseconds
// -- publishes the progress - calls the onProgressUpdate handler defined below
// -- and increments the counter variable i by one
int i = 0;
while (i <= 50) {
try {
Thread.sleep(50);
publishProgress(i);
i++;
}
catch (Exception e) {
Log.i("makemachine", e.getMessage());
}
}
return "COMPLETE!";
}

// -- gets called just before thread begins
@Override
protected void onPreExecute() {
Log.i("makemachine", "onPreExecute()");
super.onPreExecute();
}

// -- called from the publish progress
// -- notice that the datatype of the second param gets passed to this method
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("makemachine", "onProgressUpdate(): " + String.valueOf(values[0]));
_percentField.setText((values[0] * 2) + "%");
_percentField.setTextSize(values[0]);
}

// -- called if the cancel button is pressed
@Override
protected void onCancelled() {
super.onCancelled();
Log.i("makemachine", "onCancelled()");
_percentField.setText("Cancelled!");
_percentField.setTextColor(0xFFFF0000);
}

// -- called as soon as doInBackground method completes
// -- notice that the third param gets passed to this method
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("makemachine", "onPostExecute(): " + result);
_percentField.setText(result);
_percentField.setTextColor(0xFF69adea);
_cancelButton.setVisibility(View.INVISIBLE);
}
}
}


Related Topics



Leave a reply



Submit