I have an ProgressDialog where in shows while sending mail. The progress dialog works across activities and classes as one of the blog had given an hint showing ProgressDialog across activities.
Below is the code as I am overriding onCreateDialog()
#Override
protected Dialog onCreateDialog(int id) {
if(id == ID_SENDING_MAIL){
ProgressDialog loadingDialog = new ProgressDialog(this);
loadingDialog.setMessage("Sending Email...");
loadingDialog.setIndeterminate(true);
loadingDialog.setCancelable(true);
return loadingDialog;
}
return super.onCreateDialog(id);
}
then I call the mail sending as below
showDialog(ID_SENDING_MAIL);
new Thread(new Runnable(){
public void run(){//I am calling Mail Send here
dismissDialog(Email.ID_SENDING_MAIL);
}
}).start();
In run method I instantiate mail class and send host of parameters.
This is working fully but I want to set different messages to ProgressDialog.
Like at the time of connecting to Host
Sending Mail then
Mail Sent Successfully
How could we carry out those changes when used with onCreateDialog().
Looking forward to your reply.
thanks.
best way to do this by using AsyncTask:
and in onProgressUpdate(Integer... progress) use progress param to set desired messages to ProgressDialog(using swith of any other method to determine wat the exact message should be)
If you want to display different messages on different stages in network thread, then use AysncTask, and after each step in doInBackground() method, invoke publishProgress method.
in onProgressUpdate(Integer... progress) method change message in progress dialog.
Related
I have an activity. It uses nfc tag. I want to create progress dialog in method CertificateGeneration for shows steps to user. It is my code.
private void CertificateGeneration(Tag mytag)
{
ProgressDialog progress = new ProgressDialog(CertificateGenerationActivity.this);
progress.setMessage("in progress... ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();
Method1();
progress.setMessage("Method1 is executed ");
Method2();
progress.setMessage("Method2 is executed ");}
but when I execute CertificateGeneration method in debuge mode I see all lines are parse without any changes on screen.
It does not show progress Message on screen and executes method1. why?
at the end of Method (executed Method1 and Method2) It shows progress Message. and only shows " Method2 is executed".
How can I edit my code? or It a beter solution for diplay message at run time in method(not end od method)?
I also wrote a simple method too. It does not have any method. but It is executed completly and only show "progress2"
private void DisplayMsg(final String msg)
{
progress = new ProgressDialog(CertificateGenerationActivity.this);
progress.setMessage("Progress1");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();
String f="test";
progress.setMessage("progress2");
}
If you have a heavy task to done use AsyncTask.
AsyncTask has usefull methods such as publishProgress().
I've found that a lot of people are having a similar problem but I am simply trying to show a dialog while I am grabbing some data off a URL and then dismiss properly after the data is retrieved. Here is what I'm trying to do (This is in my onClick() method for a refresh button):
dialog.show();
// do some work
dialog.dismiss();
Doing it this way you never really see the dialog at all. I've tried doing it using an extra thread such as:
Thread t = new Thread() {
public void run() {
dialog.show();
}
};
But this way I get an error and a force close down...
What is the best method to do this?
For the task you are trying to implement:
dialog.show();
// do some work
dialog.dismiss();
Now, to implement above, there is concept of AsyncTask, the best way to implement Threading task, as its also known as Painless Threading in Android.
AsyncTask has 4 main methods:
onPreExecute() - Here you can show ProgressDialog or ProgressBar.
doInBackground() - Here you can do/implement background task
onProgressUpdate() - Here you can update UI based on the intermediate result you receive from webservice call or from background task
onPostExecute() - Here you can dismiss dialog or make progress bar invisible. Also you can do the task which want to do after receiving result from background task or webservice call.
For this kind of task mostly I recommend you to use the AsyncTask. Here is one good example of it which will help you.
And for this question as You are making UI related task and for that please use the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//Show or Hide your ProgressDialog
}
});
Try to use runOnUiThread of the Activity instead of using Thread.
Check the following code snippet.
runOnUiThread(new Runnable() {
public void run() {
dialog = new ProgressDialog(ctContext);
dialog.show();
}
}
});
I think this will help you.
There are a number of questions involving the lack of ability to dismiss a ProgressDialog, but none of them seem to cover my situation.
I have a Thread that runs a Runnable object that, when it completes, sends a message to a Handler object which I'm certain is sitting on the same thread as the ProgressDialog. The handler does this:
if(progressDialog != null){
Log.w(TAG, "Progress dialog is dismissed");
progressDialog.dismiss();
}else{
Log.w(TAG, "Progress dialog is null");
}
I've done this a million times before, and it's worked. The ProgressDialog goes away. But, in one particular instance, it doesn't.
In this particular case, a ProgressDialog (we'll call uploadChangesDialog) is showing, then a particular Handler (uploadChangesHandler) is called. After dismissing the uploadChangesDialog, it does a check that, if true, starts a different ProgressDialog (refreshViewDialog) and a Runnable (refreshViewRunnable) in a Thread. However, when it's Handler is called (refreshViewHandler), it can't close the dialog. But it does log Progress dialog is dismissed.
This is particularly strange, because the refreshViewsRunnable is run when the Activity is started, too, but it can get rid of the dialog then, just fine. The progressDialog variable above is the only one of it's kind, which is supposed to hold whatever ProgressDialog is currently showing.
I've done this with AlertDialogs before, but they know how to close themselves, so if I'm doing something wrong, then I wouldn't have noticed.
In the onCreateDialog() method:
case DIALOG_REFRESH_VIEW:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading details...");
progressDialog.setCancelable(false);
return progressDialog;
Copied for each instance, with a different message. I did change it to all dialogs pointing to the same code, and setting the message in onPrepareDialog(), but that didn't change any behaviour.
In the UploadChangesRunnable:
public void run(){
int result = 0;
if(uploadChanges()){
result = 1;
}
uploadChangesHandler.sendEmptyMessage(result);
}
And then in uploadChangesHandler:
public void handleMessage(Message msg){
if(progressDialog != null){
progressDialog.dismiss();
}
if(msg.what == 0){
showDialog(DIALOG_UPLOAD_CHANGES_FAILED); //This is an AlertDialog
}else{
//All this does is showDialog(DIALOG_REFRESH_VIEW) then run the thread.
//This method is in the enclosing Activity class.
refreshViewInThread();
}
}
Finally, the refreshViewInThread method:
private void refreshViewInThread(){
showDialog(DIALOG_REFRESH_VIEW);
Thread thread = new Thread(new RefreshViewRunnable(refreshViewHandler));
thread.start();
}
And the RefreshViewRunnable looks remarkably similar to the UploadChangesRunnable.
There must be some special case that makes me lose the link to my progressDialog, and the dialog that I'm dismissing is likely not the dialog that is showing, but I can't think of how that could be. Any ideas?
my guess is that this is a context/handler issue. I had a similar problem, and decided to use interfaces/callbacks instead of Handler, and it fixed my problem.
However, you could try the following, where you see this: >> But it does log Progress dialog is dismissed.<< , add:
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
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...
In my app I am doing some intense work in AsyncTask as suggested by Android tutorials and showing a ProgressDialog in my main my activity:
dialog = ProgressDialog.show(MyActivity.this, "title", "text");
new MyTask().execute(request);
where then later in MyTask I post results back to activity:
class MyTask extends AsyncTask<Request, Void, Result> {
#Override protected Result doInBackground(Request... params) {
// do some intense work here and return result
}
#Override protected void onPostExecute(Result res) {
postResult(res);
}
}
and on result posting, in main activity I hide the dialog:
protected void postResult( Result res ) {
dialog.dismiss();
// do something more here with result...
}
So everything is working fine here, but I would like to somehow to update the progress dialog to able to show the user some real progress instead just of dummy "Please wait..." message. Can I somehow access the progress dialog from MyTask.doInBackground, where all work is done?
As I understand it is running as separate Thread, so I cannot "talk" to main activity from there and that is why I use onPostExecute to push the result back to it. But the problem is that onPostExecute is called only when all work is already done and I would like to update progress the dialog in the middle of doing something.
Any tips how to do this?
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
you can update from AsyncTask's method onProgressUpdate(YOUR_PROGRESS) that can be invoked from doInBackground method by calling publishProgress(YOUR_PROGRESS)
the data type of YOUR_PROGRESS can be defined from AsyncTask<Int, YOUR_PROGRESS_DATA_TYPE, Long>