Actually I am using retrofit inside of project , and I am calling 2 Aysnc requests. but I need that after this requests success to trigger other method. how to know when this request are done and then trigger other method ?
You can use async Task in android. Here's some important highlights
create an async task
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
it will have 4 methods that you can override.
onPreExecute()
doInBackground(Params...)
onProgressUpdate(Progress...)
onPostExecute(Result)
basically, you just need to put the method that you wanna trigger in the onPostExecute method.
protected void onPostExecute(Long result) {
//add your method here
}
for more details please refer to android documentation on AsyncTask.
It seems like you're looking for this:
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am new to android, i have built an application where lot of web services are used. i am using async task doInBackground() method to make a call to webservices.
my asyntask class is public and it is written in a separate file.
i am not using onPostExecute to carry out postwebservice operations,
instead i am creating a string and returning back.
then in my activity class i am examining the string and packing the data using a java bean.
since Async task runs in an asynchronus way is it correct to rely on what doInBackground method returns. or is it must to perform my post webservice operations in onPostExecute only.
please guide me with the correct way of doing things for my project. Thanks.
Create an Interface and callback method for accessing AsyncTask class.
accessActivity or Context to ur AsyncTask using Constructor of that AsyncTask
In onPostExecute send the result to ur Activity using the
callback method
Tutorials
1.http://samir-mangroliya.blogspot.in/p/android-seperate-asynctask-class.html
2.http://www.androidsnippets.com/asyntask-in-android
3.http://www.brighthub.com/mobile/google-android/articles/82805.aspx
You should do all the post webservice work in onPostExecute, because this method is executed in the main thread (UI) an therefore you can update your UI.
Take a look at http://developer.android.com/reference/android/os/AsyncTask.html
A basic example (Taken from the docs)
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
// Here you call your webservice and return the result
return totalSize;
}
protected void onPostExecute(Long result) {
// The result from doinbackground is passed as an argument
// here, so you update your UI from this method.
}
}
As kaushik You can also reuse the Asyntask with a defined callback, check this questions:
public AsyncTask to be called from several classes
Common class for AsyncTask in Android?
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
}
I'm implementing quite a simple task - user authorization.All network operations I've implemented via AsyncTask. And I have a problem. I have two AsyncTasks - one it is authorization which calls more low level and common for all network tasks operation (JSON parsing, REST realization etc.) which also is implemented via AsyncTask. And I have a problem: onPostExecute methods of these two operations are called in a wrong order. So the question - can I someway set the order of their execution, or may be you give me some advice how to handle all this in a right way.But don't suggest me to refuse AsyncTask and use something else. I want a right solution with AsyncTask. Thanks in advance.
It sounds like you should have a single AsyncTask for the high-level background operation. The low-level network activities should be invoked directly in the high-level doInBackground. By having two AsyncTasks running, you lose the ability to easily coordinate the timing of their individual work.
If for some reason you need to independently run the lower-level operations in an AsyncTask (that is, for purposes other than authorization), then that AsyncTask should also directly invoke the low-level network activities from its own doInBackground; however, the low-level activities should still be separate from any AsyncTask.
Run your 2. asycTask in 1. fisrt asycTask onPostExecute method. By the way you can set its order yourself.
like below,
private class task1 extends AsyncTask<URL, Integer, Long> {
protected int doInBackground(URL... urls) {
// do your stuf
return 1;
}
protected void onPostExecute(int result) {
// first task finished and second task starts
new task2().execute();
}
}
private class task2 extends AsyncTask<URL, Integer, Long> {
protected int doInBackground(URL... urls) {
// do your stuf
return 1;
}
protected void onPostExecute(int result) {
// do your stuf
}
}
Consider the scenario where I have get data from server and post it to UI in say list view , but this is an going activity ,it never stops.
taskA{ //fetches data over network
if(!update)
fetch();//network operation
}
taskB{//using this data UI is updated at runtime just like feed.
if(update)
show();//UI operation
}
taskA starts first after it completes taskB starts by that time A is sleeping and vice versa , goes , now the problems i am facing are:
both operations have to be in worker thread
both operations are going in cycle till activity is alive.
if handler is used to post UI operation to the main thread , taskB seems to stop.
Can anybody please suggest me a design to get this working?
AsyncTask is doing the job for you. You can make it as an inner class under your Activity main class.
http://developer.android.com/reference/android/os/AsyncTask.html
Example code
private class YourTask extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
// Fetch Data (Task A)
return "Result";
}
protected void onProgressUpdate(Integer... progress) {
// Show progress
}
protected void onPostExecute(String result) {
// Show UI after complete (Task B)
}
}
AsyncTask is what you're looking for. Check out this link for some sample code:
http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/
You can also use IntentService you can check some sample code
An Android service is lightweight but more complex to setup.
AsyncTask is very easy but not recommended as it has many downsides and flaws.
You could also look into Loaders but it's not as easy as AsyncTasks.
I am developing an application for blind people. I have to work all the time with the TextToSpeech module, GPS and Network connection.
I need to do a query like this: Consult the GPS, do a JSON call and calling the TextToSpeech(TTS) module.
I am wondering the best way to deal with the different tasks which communicate with the UI main thread. I have seen so far:
Handler objects and AsyncTask class.
I have to launch each task sequentially, so I want to call the TTS after retrieving data from the network. So I have used "mHandler.post(Runnable)" and inside that runnable calling another one and so on.
However I have seen that is recommendable the use of the AsynTask class. But in this case I think I have to implement a different class for every task, whereas I don't know if those tasks will execute sequentially. Something like:
AsyntaskClass1 at1;
AsyntaskClass2 at2;
AsyntaskClass3 at3;
at1.execute();
at2.execute();
at3.execute();
Will that tasks execute in order? Cause the TTS module have to wait for the network task to finish...
Thanks for your help,
BR.David.
You could everything with a single AsyncTask class:
private class AsyncTask1 extends AsyncTask<Object, Void, Object> {
#Override
protected String doInBackground(Object... args) {
// Get a result from the GPS.
// Make a network call
// Communicate with the TTS
}
#Override
protected void onPostExecute(Object result) {
// Return a result to the main thread
// You are only allowed to touch the UI here
}
}
No they will be executed almost simultaneously... i.e. the second asynctask will not wait for first one to finish.
I suggest you to club all the tasks in one single AsyncTask and use publishprogress() to update the UI after each task finishes.
so you can start that AsyncTask after the network finishes and the UI will get updated sequentially
eg.
public Object doInBackground(Object... params){
//do task one's stuff
publishProgress(1);
// do task two's stuff
publishProgress(2)
//do task 3
publishProgress(3)
}
public void onProgressUpdate(Integer... int){
switch(int[0]){
case 1:
//ui update for task 1
case 2:
//ui update for task 3
case 3:
//ui update for task 3
}
The execution order is not guaranteed in your example. The UI thread would launch the 3 AsyncTasks. These three tasks would then execute concurrently.
If you want to execute the code in the tasks synchronously you have at least a couple of ways to acomplish it:
Combine the three tasks into one where you have ordered the work to be done sequentially i.e:
AsyncTaskCombined task = new AsyncTaskCombined();
task.execute();
private class AsyncTaskCombined extends AsyncTask<Void, Void, Void> {
protected Bitmap doInBackground(Void... urls) {
// Initialize classes that implement the work logic
Work1 work1;
Work2 work2;
Work3 work3;
// Do the work sequentially...
work1.doWork();
work2.doWork();
work3.doWork();
}
}
Or potentially you could have 3 different AsyncTask and then in the onPostExecute of the first task create and call the second AsyncTask and in the second AsyncTask's onPostExecute create and call the third and last AsyncTask. However that seems a bit contrieved to me...
// Emil H