Abort AsyncTask within the AsyncTask - android

How to cancel a AsyncTask from a ProgressDialog implemented within this AsyncTask.
#Override
protected Void doInBackground(Void... params)
{
try
{
FTPHelper ftpHelper = new FTPHelper(_context);
ftpHelper.SincronizarArquivos();
}
catch...
#Override
protected void onPreExecute()
{
_dialog.setMessage("Aguarde, sincronizando arquivos...");
_dialog.setCancelable(false);
_dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancelar", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// This not works for cancel AsyncTask
cancel(true);
...
Since there is no loop in doInBackground (Void ... params) has as I cancel or return. How can I cancel AsyncTask from ProgressDialog?

Both the dialog and the AsyncTask have a 'cancel' method, so when you call cancel in the dialog it cancels the dialog.
The solution is for the dialog to call the cancel function of the AsyncTask. From the code in the question I can't quite infer the way the dialog and the task are linked in the code, but in essence, if ...
AsyncTask myAT;
Then within the dialog:
myAT.cancel();

Call
MyAsyncTask.this.cancel(true);
inside the Dialog.
Here MyAsyncTask is the name of your AsyncTask subclass.
NOTE: This will work (only) if the Dialog was instantiated inside the AsyncTask

Related

Android AsyncTask cancel with message

I have an AsyncTask that shows a dialog when runing. When i click cancel :
if (isCancelled()) break;
How to display a message in a dialog ( with "ok" button ) when i cancel the asyncTask?
Thanks
AsyncTask has a method just for that
#Override
protected void onCancelled() {
super.onCancelled();
// Show the dialog
}
onCancelled is only called if cancel is called. However note the docs: Runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished.
This means onCancelled will not be called immediately on any thread.
You just have to create an alert dialog and display it in the onCancelled method of AsyncTask
#Override
protected void onCancelled() {
super.onCancelled();
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.show();
}
});
}
To know on creation of dialog, you can follow this: Alert dialog with a button

Show ProgressDialog when loading heavy UI

I use asynctask quite often however this time it doesn't work!
I have a UI contains a viewpager and fragments. To populate the view, it takes about 3 secs. Now I want to show the ProgressDialog until it finishes by using AsyncTask. But the ProgressDialog is not showing!!!!
Anybody can tell me the solution? Thanks
onCreate(...){
setContentView(...)
new LoadUI(MyActivity.this).execute();
}
public class LoadUI extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
Context context;
public LoadUI(Context mContext) {
this.context = mContext;
pd = new ProgressDialog(mContext);
aViewPager = (ViewPager) findViewById(R.id.aPagerDay);
}
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
//Create ViewPager
//Create pagerAdapter
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd.isShowing()) {
pd.dismiss();
}
super.onPostExecute(result);
}
}
You can try out two options:
Either use the AsyncTask's method get(long timeout, TimeUnit unit) like that:
task.get(1000, TimeUnit.MILLISECONDS);
This will make your main thread wait for the result of the AsyncTask at most 1000 milliseconds.
Alternatively you can show a progress dialog in the async task until it finishes. See this thread. Basically a progress dialog is shown while the async task runs and is hidden when it finishes.
You have even third option:" if Thread is sufficient for your needs you can just use its join method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
The problem is the GUI is not ready in onCreate(). And nothing will be shown if I try to show Dialog in this state. A solution is move the dialog to activity onStart():
#override
onStart(){
new LoadUI(MyActivity.this).execute();
}

Is doInBackground Cancelled when dialog dismisses?

I have a custom progress dialog within an AsyncTask which acts as a download progress, I want to interrupt doInBackground when my custom cancel button pressed. It seems when the dialog dismisses, doInBackground resumes without any problems!
I want to interrupt doInBackground when my custom cancel button pressed.
=> call cancel() method of your AsyncTask inside the cancel button click event. Now this is not enough to cancel doInBackground() process.
For example:
asyncTask.cancel(true);
To notify that you have cancelled AsyncTask using cancel() method, you have to check whether its cancelled or not using isCancelled() inside doInBackground().
For example:
protected Object doInBackground(Object... x)
{
// do your work...
if (isCancelled())
break;
}
You could call AsyncTask.cancel(true) from the cancel event of the dialog. For this you do need a reference to the AsyncTask, this could be an instance variable initialized when the task is started. Then in the asyncTask.doInBackground() method you can check for isCancelled(), or override the onCancelled() method and stop the running task there.
Example:
//Asynctask instance variable
private YourAsyncTask asyncTask;
//Starting the asynctask
public void startAsyncTask(){
asyncTask = new YourAsyncTask();
asyncTask.execute();
}
//Dialog code
loadingDialog = ProgressDialog.show(ThisActivity.this,
"",
"Loading. Please wait...",
false,
true,
new OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
if (asyncTask != null)
{
asyncTask.cancel(true);
}
}
});
EDIT: If you create the dialog from inside the AsyncTask, the code would not be very different. You probably wouldn't need the instance variable, I think you could call YourAsyncTask.this.cancel(true) in that situation.

Make a transition between activitys

I need to make a transition screen, ou just put a dialog, because the app give a black screen when is creating the database.
I have google, and find some solutions for this. One of then, is just put a progress dialog when the database is been created.
My problem, and newbie question is, where do i put the progress dialog.
A -> BlackScreen -> B where A is the inicial menu, and B the other screen. I have tried to put the dialog on A and/or in B and dont work. So where can i put the code of the progress dialog, so it shows in the BlackScreen ?
Make use of Asyntask . put your database operation of creating database in asyntask in pre execute start dialog post execute cancel dialog in background perform database operation
http://developer.android.com/reference/android/os/AsyncTask.html
For that You have to use Async task :
class DownloadAsyncTask extends AsyncTask<String, String, Void>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Login.this, "", "Please Wait ...");
}
#Override
protected Void doInBackground(String... arg0) {
//Do your Task
}
#Override
protected void onProgressUpdate(String...values){
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
}
}
//Create the Object
DownloadAsyncTask downloadAsyncTask = new DownloadAsyncTask();
downloadAsyncTask.execute();
now till your work get's completed it shows progress dialog inside the doInbackground write your logic and onPostExecute dismiss the dialog and call Intent of other Activity.

ProgressDialog communicate with AsyncTask in android

Tips or ideas on how ProgressDialog can communicate with asyncTask.
For example when I click the button, the program will validate the input to internet, This is should not be interupted. so I use ProgressDialog.
After progressDialog.dismiss(), I need to refresh the view by calling the asyncTask.
I have tried some ways but it's failed, for example
* I execute asynTask after progressdialog.dismiss().
* put execution asynctask inside dialogbox after progressdialog thread.
in other word, is there any way to tell asynctask that progressdialog has been dismissed. Or is there communication such as message between threads ?
here is the example of my code:
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stockProgressDialog = ProgressDialog.show(PostActivity.this,
"Please wait...", "Check the post");
new Thread() {
public void run() {
try{
/* Connect to Internet API */
stockProgressDialog.dismiss();
} catch (Exception e) { }
// Dismiss the Dialog
}
}.start();
new LookUpTask().execute();
}
});
Yes, there is a way to tell asyncTask that progressDialog has been dismissed. you can use one onDismissListener
#Override
public Dialog onCreateDialog(int id){
if(id==DIALOG_PROGRESS_DIALOG){
stockProgressDialog = new ProgressDialog(Main.this);
stockProgressDialog.setTitle("Please wait...");
stockProgressDialog.setMessage("Check the post");
stockProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
textView.setText("Waiting the 5 secs...");
myAsyncTask.execute("start it");
//Or myAsyncTask.cancel(true); if you want to interrupt your asyncTask
}
});
return stockProgressDialog;
} else return super.onCreateDialog(id);
}
You can cancel an AsyncTask by calling AsyncTask.cancel(..) and then start up a new AsyncTask. You are not supposed to run the AsyncTask as a parallel activity - it is supposed to be able to run and finish without outside intervention.
Extend async and look into returning a result from doInBackground. onProgress update can dismiss your Progress dialog under control of the async task. Handle the result from doInBackground in onPostExecute.
//create the task
theBackground = new Background();
theBackground.execute("");
--------
private class Background extends AsyncTask<String, String, String>{
protected String doInBackground(String...str ) {
publishProgress("##0");
//do a bunch of stuff
publishProgress(#001);
return("true");
}
protected void onProgressUpdate(String... str ) {
//do stuff based on the progress string and eventually
myProgressDialog.dismiss();
}
protected void onPostExecute(String result) {
}
}
I'm not sure why you're using a thread in one case, but an AsyncTask in another when you could just use two AsyncTasks... Actually, unless I'm missing something, in your case the most straightforward way is to combine the two bits of work into one AsyncTask and simply create and destroy the dialog in the AsyncTask callbacks. In pseudo-code:
onPreExecute
show dialog
doInBackground
do internet stuff
onPostExecute
update views
close dialog
Is there a reason why you're trying to update the views in its own AsyncTask? If you're updating views, you probably need to do the work in the UI thread anyway...

Categories

Resources