Hi friends,
After some months of experience in Android, I got some issue with canceling ProgressDialog.
Default behavior is, you can cancel Dialog by pressing back “key”.
I got issue in this that, My task was not canceled.
I realized that AsyncTask is separate thread, you need to call .cancel() method.
I also realized that my custom image gallery was eating lots of internet call, because of AsyncTask was not canceled.
Cancelling an AsyncTask is not easy as it looks. You need to take care of it’s state, make use of onCancelled() call etc, notifying correct message to user etc.
All this thing is explained by taking an example of login activity.
Please read all the comments on following code:
package com.isummation.exampleapp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URLEncoder; import java.net.UnknownHostException; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class UserLogin extends Activity { private EditText etUsername; private EditText etPassword; private ProgressDialog progressDialog; private static final int PROGRESSDIALOG_ID = 0; private static final int SERVER_ERROR = 1; private static final int NETWORK_ERROR = 2; private static final int CANCELLED = 3; private static final int SUCCESS = 4; private String ServerResponse; private LoginTask loginTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); etUsername = (EditText) findViewById(R.id.txt_username); etPassword = (EditText) findViewById(R.id.txt_password); Button login_button = (Button) this.findViewById(R.id.login_button); login_button.setOnClickListener(new OnClickListener() { public void onClick(View viewParam) { if (etUsername.getText().toString().length() == 0 || etPassword.getText().toString().length() == 0) { Toast.makeText(getApplicationContext(), "Please enter username and password", Toast.LENGTH_SHORT).show(); } else { //Show dialog by passing id showDialog(PROGRESSDIALOG_ID); } } }); } protected Dialog onCreateDialog(int id) { switch(id) { case PROGRESSDIALOG_ID: removeDialog(PROGRESSDIALOG_ID); //Please note that forth parameter is true for cancelable Dialog //Also register cancel event listener //if the litener is registered then forth parameter has no effect progressDialog = ProgressDialog.show(UserLogin.this, "Authenticating", "Please wait...", true, true, new OnCancelListener(){ public void onCancel(DialogInterface dialog) { //Check the status, status can be RUNNING, FINISHED and PENDING //It can be only cancelled if it is not in FINISHED state if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) loginTask.cancel(true); } }); break; default: progressDialog = null; } return progressDialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case PROGRESSDIALOG_ID: //check if any previous task is running, if so then cancel it //it can be cancelled if it is not in FINISHED state if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) loginTask.cancel(true); loginTask = new LoginTask(); //every time create new object, as AsynTask will only be executed one time. loginTask.execute(); } } class LoginTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... unused) { try { ServerResponse = null; //don't forget to make it null, as task can be called again HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet( getString(R.string.WebServiceURL) + "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=" + URLEncoder.encode(etUsername.getText() .toString(), "UTF-8") + "&password=" + URLEncoder.encode(etPassword.getText() .toString(), "UTF-8")); httpClient.getParams().setParameter( CoreProtocolPNames.USER_AGENT,"Some user agent string"); //call it just before you make server call //calling after this statement and canceling task will no meaning if you do some update database kind of operation //so be wise to choose correct place to put this condition //you can also put this condition in for loop, if you are doing iterative task //now this very important //if you do not put this condition and not maintaining execution, then there is no meaning of calling .cancel() method //you should only check this condition in doInBackground() method, otherwise there is no logical meaning if (isCancelled()) { publishProgress(CANCELLED); //Notify your activity that you had canceled the task return (null); // don't forget to terminate this method } HttpResponse response = httpClient.execute(httpGet, localContext); BufferedReader reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent(), "UTF-8")); ServerResponse = reader.readLine(); publishProgress(SUCCESS); //if everything is Okay then publish this message, you may also use onPostExecute() method } catch (UnknownHostException e) { removeDialog(PROGRESSDIALOG_ID); e.printStackTrace(); publishProgress(NETWORK_ERROR); } catch (Exception e) { removeDialog(PROGRESSDIALOG_ID); e.printStackTrace(); publishProgress(SERVER_ERROR); } return (null); } @Override protected void onProgressUpdate(Integer... errorCode) { switch (errorCode[0]) { case CANCELLED: removeDialog(PROGRESSDIALOG_ID); Toast.makeText(getApplicationContext(), "Cancelled by user", Toast.LENGTH_LONG).show(); break; case NETWORK_ERROR: removeDialog(PROGRESSDIALOG_ID); Toast.makeText(getApplicationContext(), "Network connection error", Toast.LENGTH_LONG).show(); break; case SERVER_ERROR: removeDialog(PROGRESSDIALOG_ID); Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_LONG).show(); break; case SUCCESS: removeDialog(PROGRESSDIALOG_ID); try { if (ServerResponse != null) { JSONObject JResponse = new JSONObject(ServerResponse); String sMessage = JResponse.getString("MESSAGE"); int success = JResponse.getInt("SUCCESS"); if (success == 1) { //proceed further //you may start new activity from here //after that you may want to finish this activity UserLogin.this.finish(); //Remember when you finish an activity, it doesn't mean that you also finish thread or AsynTask started within that activity //So you must implement onDestroy() method and terminate those threads. } else { //just showing invalid username password from server response Toast.makeText(getApplicationContext(), sMessage, Toast.LENGTH_SHORT).show(); } } } catch (Exception e){ Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_LONG).show(); e.printStackTrace(); } break; } } @Override protected void onPostExecute(Void unused) { } } @Override protected void onDestroy(){ //you may call the cancel() method but if it is not handled in doInBackground() method if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) loginTask.cancel(true); super.onDestroy(); } }
Please feel free to ask/comment.
u can check network connection by
private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
tryLogin();
return true;
} else {
Toast.makeText(Login.this, “Internet Connection Not Present”, Toast.LENGTH_LONG).show();
Log.v(TAG, “Internet Connection Not Present”);
return false;
}
}
This work well on device. But do some other testing. Try to disable network adapter of pc, then check it in emulator. This method will not work as it is still connected to 10.0.2.2 i.e. pc’s localhost!
see my comment here
hi, I m not getting why u want to disable LAN connection,any way as per my knowledge, check ur logcat ,if you are getting exception of “java.net.UnknownHostException: http://www.urweb.com“, and you can handle this by try{ urLoginProcess….. }catch (IOException e) {e.printtrace();}
and one more tips if u use my “checkInternetConnection()” in thread then it be faster as like
showDialog(0);
t = new Thread() {
@Override
public void run() {
Looper.prepare();
checkInternetConnection();
removeDialog(0);
}
};
t.start();
and one more thing ur link “here” is not working plz check it, i ll try if i can give you better solution
Check the link now…
OK, Its working, but sry I can’t help you more on regarding current topic, bcz as per my above suggestion i ve tried with above my code and it working perfect(not FC) even if LAN is disable… any way all D best
how to down;load source code? i didnot find xml
Hello and thanks for the post.
If you can help me with this
http://stackoverflow.com/questions/16582484/progress-bar-remains-empty-using-asynctask-edit-dialog-never-stops-loading
I ‘ll appreciate it.
Exept from the problem I have with dialog ,I can’t terminate the task also.
Thanks!
hi..i am new to android development, i m using mysql as backend.servlet(webservice) to communicate with database.i tried your login code.u have mentioned some code like as parameter to WebServiceURL,””/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=”.
what is it actually??webservice page URL after running on browser??
” if (isCancelled()) {
publishProgress(CANCELLED);
return (null); // don’t forget to terminate this method
}”
in this statement the publishProgress(CANCELLED) is never called when the task is cancelled. But it does call the @Override onCancelled() method for the async task.
Can you explain if this is true.
Plus size women can now get maternity clothes for childbirth and later for nursing the baby as well as brassieres and nighties they can put on after the baby has been born. You take in right, obtain a good amount
of exercise together with ensure you attend to the actual skin.
Consumers are savvy and will shop around for
the best deals; with the advent of the internet shoppers now realize that high
street stores are no longer the best places to find a bargain.
One other gift basket variation would be a “sexy” gift basket loaded with eatable lotions, a bottle
of champagne and naughty games or perhaps toys.
Buying from an online wine retailer will mean that you
can complete your gift shopping in the cosy surroundings of your own home without the hustle and bustle of supermarket trolleys, Christmas Shoppers and pushy
sales assistants. A while back I dated a guy for about two years,
he was the best “gift giving” guy I’ve ever met in my life.
The main aim of such an approach is to plan the poses to make sure that beautiful pictures of the couple are
clicked while also making sure that the photographs look
absolutely random and very natural. This should basically be a quick bio
of the owner and managers. If you find them irritating in the initial meeting, you will likely find them irritating on the wedding day.
Thank you for another magnificent article.
The place else may just anyone get that type of info in such an ideal
approach of writing? I’ve a presentation subsequent week, and
I am on the look for such information.
Thanks for finally talking about >Android – Proper way
to cancel AsyncTask | Vikas Patel’s Blog <Loved it!
I think what you composed made a ton of sense. However,
what about this? what if you added a little content?
I mean, I don’t want to tell you how to run your blog, but suppose you added something that grabbed folk’s attention? I mean Android – Proper way to cancel AsyncTask | Vikas
Patel’s Blog is kinda vanilla. You should look at Yahoo’s
front page and see how they write post titles to get viewers to click.
You might add a related video or a related pic or two to get people
interested about what you’ve got to say. Just
my opinion, it might make your posts a little livelier.
It’s nearly impossible to find educated people
in this particular topic, but you seem like you know what you’re talking about!
Thanks
It’s truly a nice and helpful piece of information. I’m glad that you
simply shared this helpful information with us. Please stay us
informed like this. Thank you for sharing.
I simply couldn’t depart your website before suggesting that I actually enjoyed the standard information a person provide
to your visitors? Is gonna be back incessantly to check up on new posts
obviously like your web site but you need to check the spelling on quite a few of your posts.
Several of them are rife with spelling problems and I to find it
very bothersome to tell the truth nevertheless I
will definitely come back again.
My partner and I stumbled over here different web
page and thought I should check things out. I like what I see so now
i am following you. Look forward to exploring your web page yet again.
you are in point of fact a good webmaster. The site loading pace is amazing.
It kind of feels that you’re doing any unique trick. Also,
The contents are masterpiece. you have performed a great process in this matter!
If some one wants to be updated with hottest technologies then he must be go to see this web page and
be up to date all the time.
I couldn’t resist commenting. Very well written!
Hello my friend! I wish to say that this article is amazing, great written and come with almost all
important infos. I would like to see extra posts like this .
Nice blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple adjustements would
really make my blog jump out. Please let me know where you got your design. With thanks
Thank you for the auspicious writeup. It actually was a enjoyment account it.
Glance complex to more introduced agreeable from you!
However, how can we communicate?
Usually I do not read article on blogs, but I wish to say that this write-up very forced me to take
a look at and do so! Your writing taste has been amazed me.
Thank you, quite nice article.
Good day! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community
in the same niche. Your blog provided us valuable information to work on. You have
done a marvellous job!
Reblogged this on sivabe35 and commented:
Asyntask cancel Very useful in Fragments