synchronize method with progress dialog - android

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
}

Related

How to update a View before heavy freezing method?

I use a code that access HTTP service to receive login data, and before it, I tried to show a processing dialog, but it did not showed up. Then I tried to simply change the button label to tell the user to wait until data returns, but it also did not work. That's my code:
tryingToLoginDialog = ProgressDialog.show(this, "Por Favor Aguarde", "Efetuando Login...", true);
btn_Entrar.setText("Wait while logins...");
btn_Entrar.invalidate();
App.webService.Login(txtLogin.getText().toString(), txtSenha.getText().toString());
String LoginUserData = App.webService.getUserData(); /* this method freezes the app but do not crash it cause ThreadPolicy permit all*/
/* here some if's */
tryingToLoginDialog.dismiss();
btn_Entrar.setText("Login");
btn_Entrar.invalidate();
You should use AsynTask. This has 4 different method doInBackground() This method run in background(not in UI Thread) In your case you can do your networking stuff here and other three methods are onProgressUpdate(), onPostExecute() and onPreExecute() run in UI Thread So you can use these function to update GUI.
You were saying you want to show dialog so setup progressdialog in onPreExecute() and do your freezing stuff in doInBackground() and use other method according to your need.
See detail here

Cancel Android asyncTask progress Dialog

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

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
}

Handle single progressdialog with parallel multiple asynctask

In my Project I want to parallelly load the data from 3 different url's(webservice) while loading the page.
for this I use 3 different asynctask to load data.
I want to show the progress dialog message as "loading" when first asynctask is started and close dialog after last asynctask is completed(until complete 3 tasks show progress dialog).
Please tell me the way to handle this situation.
There are different ways to handle this situation.
You can use a counter variable initialized with the number of tasks, and this counter gets decremented when an AsyncTask is complete. When the counter is 0, the ProgressDialog is dismissed. You can do this decrement and checking for progress dialog dismissal in each of the AysncTask's onPostExecute.
You may not need the 3 different AsyncTasks. You can use a single AsyncTask with a CountDownLatch for Thread synchronization.
One way you can do is you can create an interface OnThreadFinishListener (with an onThreadFinish() method) and have your activity implement it. All of your AsyncTask should register itself to the listener so each time a thread finishes it calls the onThreadFinish method. in the onThreadFinish method it should check if there is still a thread running in the background (something like if (asyncTask1.getStatus() == AsyncTask.Status.RUNNING || asyncTask2.getStatus() == AsyncTask.Status.RUNNING ... ) )
If all are false then you can dismiss the progress dialog.
You may do it as below:
//define progress dialog object globally in your parent class
ProgressDialog pd = null;
AsyncTask1 onPreExecute:
pd = ProgressDialog.show(this, "title", "loading", true);
AsyncTask2:
//do nothing
AsyncTask3 onPostExecute:
if(pd!=null)
pd.dismiss();

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().

Categories

Resources