Cancel Android asyncTask progress Dialog - android

I have an android application that employs AsyncTasks with progress dialogs.
My problem is that although i have managed to cancel the AsynchTasks i get
Activity ... has leaked window
Its because even though i have managed to cancel the asynchTask i havent cancelled the progress dialog.
how can i guarantee to cancel the asynctasks progress dialog?
#SuppressWarnings("rawtypes")
public OnCancelListener buildOnCancelListener(final AsyncTask asyncTask) {
return new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialogInterface) {
asyncTask.cancel(true);
}
};
}

Put yourDialog.dismiss(); in the onCancelled method and in onPostExecute. If you are using AsyncTask.cancel(...) the onCancelled() will be invoked after doInBackground() NOT onPostExecute().
This is documented here.

This is because you're trying to move to a new Activity without dismissing the Dialog first.
You can try this:
use publishProgress() and onProgressUpdate() in AsyncTask to update the ProgressDialog.
in onProgressUpdate() tests for the dialog to be visible/alive before trying to update it. This will not bring any synchronization issue since onProgressUpdate run in the same UI Thread of the activity.
call dialog.dismiss() both on onCanceled() and onPostExecute().
be sure to call dialog.dismiss() in Activity.onStop() if your dialog is already visible.
Calling dialog.dismiss() in onCancel() will not guarantee that the problem is solved since

Related

Waiting till the async task finish its work

I'm very new to programming and I have some doubts.
I have a AsyncTask which is I call as RunInBackGround.
and I start this process like:
new RunInBackGround().execute();
But I wish to wait until this call is finish its executing, before proceeding to the other statements of code.
How can I do that?
Are there any way for it?
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask as :
String str_result= new RunInBackGround().execute().get();
Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.
You've got pretty much 2 options here;
You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.
If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.
In your AsyncTask add one ProgressDialog like:
private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);
you can setMessage in onPreExecute() method like:
this.dialog.setMessage("Processing...");
this.dialog.show();
and in your onPostExecute(Void result) method dismiss your ProgressDialog.
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute() it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
#Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
#Override
public void processFinish(String data) {
// do things
}

When I developing an Android application ,how can I cancel a running AsyncTask? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ideal way to cancel an executing AsyncTask
When I developed an Android application, I used an AsyncTask to download something, I used a progressDialog to show the progress of this AsyncTask, now When I press the back button, I want to cancel this AsycTask, I invoked the AsycTask.cancel(), but it doesn't work. How can I cancel a running AsyncTask ?
class ImplementAsynctask extends AsyncTask implements OnDismissListener{
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
protected onPreExecute() {
//do something and show progress dialog
}
protected onPostExecute() {
//cancel dialog after completion
}
#Override
public void onDismiss(DialogInterface dialog) {
//cancel AsycTask in between.
this.cancel(true);
}
};
The most correct way to do it would be to check periodically inside doInBackground if the task was cancelled (i.e. by calling isCancelled). From http://developer.android.com/reference/android/os/AsyncTask.html:
Cancelling a task :
A task can be cancelled at any time by invoking
cancel(boolean). Invoking this method will cause subsequent calls to
isCancelled() to return true. After invoking this method,
onCancelled(Object), instead of onPostExecute(Object) will be invoked
after doInBackground(Object[]) returns. To ensure that a task is
cancelled as quickly as possible, you should always check the return
value of isCancelled() periodically from doInBackground(Object[]), if
possible (inside a loop for instance.)
Check also this blog post if you need more information: http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/
do the following on click of back button:
declare your Aynctask as global variable like this:
//AysncTask class
private contactListAsync async;
if(async != null){
async.cancel(true);
async= null;
}

synchronize method with progress dialog

I have loadData() which used to load my Neuroph network.
I want to run it with a progress dialog but if part of loadData() execute i increase my progress dialog.
I need tutorial for it.
I know Thread with Handler, AsyncTask. but cannot do that with these two methods.
So i recommend to you use meant AsyncTask that is specified for updating UI with some progress. This tool contains three the most important methods:
doInBackground - It's doing your work in background Thread.
onProgressUpdate - For updating your UI(in your case here you can incrementing your progress for ProgressDialog)
onPostExecute - It's called after your work finished.
Then, AsyncTask is strong tool, is very efficient and also using generics so is type-safe. But you need to read more about it so first have look at reference and then i recommend to you have look at Android Threads, Handlers and AsyncTask on Vogella, it's great source.
Then you want to use ProgressDialog.
So simply create it and show() it before you execute AsyncTask. Then in onPostExecute method you just call dismiss method for dismissing ProgressDialog.
ProgressDialog pd = new ProgressDialog(this);
pd.setProgress(0);
pd.setTitle("Some title");
pd.setMessage("Some message...");
pd.show();
yourTask.execute(); // here you are executing your AsyncTask
Then in your OnPostExecute method just call dismiss:
#Override
protected void onPostExecute(Void unused) {
pd.dismiss(); // dismissing your ProgressDialog
}

Progress Dialog in Android with some background logic gives Handler Error?

Anybody has any idea about ProgressDialog of Andorid with Thread? I am successfully able to display the dialog and dismiss it also, but I have some long logic to be done and then only to dismiss the dialog, until that dialog will display loading message. I put my logic code inside the Run method of thread with While condition that until I didn't get particular result it will run the code. But somehow it is giving Handler and Looper.prepare() error. I try to found this and get to know that I have to use the functionality of Handler class.
ProgressDialog comes under UserInterface.Donot dissmis it inside thread and show before starting thread;
like this.
Thread th=new Thread(this);
ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Loading...");
pd.show();
th.start();
Now take handler class to dismiss it
void run(){
///do your work;
handler.sendEmptyMessage(0);
}
private Handler handler=new Handler(){
//override onhandle message method and dismiss dialog in it
}
For the same, you can implement AsyncTask concept, and which is very much preferable in Android to implement threading task, by implementing this task, system itself handles the threading task like start, run, stop....etc. and that's why its known as as Painless Threading.
If you have gone through AsyncTask link then i am sure you have noticed those 4 methods of AsyncTask.
For your problem, you can implement the AsyncTask as below:
onPreExecute() - Display progress dialog
doInBackground() - implement all the long running task
onPostExecute() - dismiss progress dialog by calling dialog.dismiss();
I am sure you got it now.
All the best.
Update:
you just need to write Dialog.Show() method inside the onPreExecute() method, and dialog.dismiss() inside the onPostExecute() method. And yes i have told 1000 times that you can't write Toast directly inside the doInBackground() method because Android doesn't allows to ride on the main thread, and if you still want to execute it then write the same Toast message inside the runOnUiThead method (this method should be inside the doInBackground().

Progress Dialog Box Won't appear - Android

I want to make a Progress Dialog Box in my app to use when sending some information. But the code I wrote won't work. It the method send() executes but the dialog box never appears because it dismisses very quickly
Here is my code :
ProgressDialog myProgressDialog = ProgressDialog.show(Tents.this,
"Please wait...", "Sending...", true);
send();
myProgressDialog.dismiss();
goFour();
How do I make the Dialog Box Last a little longer?
First of all - you should not do send() in the same thread as show() and dismiss() - because you are effectively blocking UI thread during sending. The dialog will actually never show - because in order to show it after show() is called, you need to give the control back to the main looper in UI thread and simply finish handling whatever event you are handling. Otherwise the UI thread will never have a chance to draw your dialog.
The best idea is to start running send() in AsyncTask and call dismiss() in onPostExecute() (see http://developer.android.com/reference/android/os/AsyncTask.html to get idea how to run async task).
You are probably getting a progress dialog, but having it immediately dismiss as it has nothing to wait for.
I'll pretend you want this in OnCreate for my example:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressDialog pd = ProgressDialog.show(this, "Please wait...", "Sending...");
new Thread(new Runnable(){
public void run() {
send();
pd.dismiss();
}
}).start();
gofour();
}
EDIT: If it still goes away immediately, make sure send(); does something that actually takes some time. ;)
The UI thread is used to start send() , this will not work and progress dialog will not be shown .
Call send in another thread or AsynTask doBackground and on completion dismiss the dialog.
If your send action is completing so quickly that the dialog is not displaying properly, might I suggest instead using an indeterminate progress bar in the upper right corner of your activity via requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS) and then utilizing setProgressBarIndeterminateVisibility(true/false).
"I guess my real question would then be how do I make it so that it lasts a little longer?" My answer would be WHY???!!!
I think you would be better showing an alert dialog to confirm your send function has completed, it would be annoying for the user having to wait for no reason!

Categories

Resources