This is my problem..i am calling a method in doInBackground of my AsyncTask class, the method is declared in my main activity class. Does it work in background thread? or i need to write the whole method inside the doInBackground ??
protected String doInBackground(String... params) {
getAllUsersfromServer();
return null;
}
this getAllUsersfromServer(); is declared in the main class. the method download some data from server using REST..
I need to run this whole process in background thread. Does it works?
Does it work in background thread?
AFAIK, Yes it works in background thread.
do I need to write the whole method inside the doInBackground ??
No need to do that.
onPostExecute works very next moment.. even my users information are
still loading
This is the main point, Its just working line by line, when it goes to execute getAllUsersfromServer(); the control goes to execute that method which gets executed in Another Background Thread. [To understand add one log print line below the method call in doInBackground and one in the method's loop and you will see even if the loop doesn't complete the doInBG log will get printed]
This happens because, your method getAllUsersfromServer(); is Void, and the Android takes it as some other independent work to be done and doesn't wait till it gets complete and keep moving to next lines.
Solution :
Just add one return type i.e. boolean getAllUsersfromServer(); and add return statement in the method return true; and in your doInBackground boolean flg = getAllUsersfromServer();
AsyncTask method doInBackground works asynchronously in a separate thread and your main thread remains available to display UI.
However what we usually do is that network processing such as "getAllUsersFromServer" is done using static HttpHelper class or method etc.
Yes it will work in the background thread. check this
I don't know why you would want to do that, but anyhow:
You'll have problems if the activity is destroyed during the async call, like if there's an orientation change. A solution to that would be to make the method static.
Related
My situation is this:
first I call first AsyncTask which fetched required Items from database. After that, I call another AsyncTask, which fetches these Item images.
I am getting data from AsynTasks by using callback.
Here is the issue - since I am using callback, in my class I have method processFinish which returns AsyncTask data when it finishes its computation. The problem is with two Async tasks which depend on each other. What should I do now?
You can use the get() method of asyncTask that will wait for the output and wont proceed further
also you can use it with a timeout.
ex new BackgroundTask().execute.get();
or
new BackgroundTask.execute.get(long timeout);
You could execute one AsyncTask inside another, but you should do it inside onPostExecute() because this method runs on the UI thread.
#Override
protected void onPostExecute(Void args) {
new AsyncTask2.execute(..); // Start second task once you've got first results
}
And you call your method processFinish(..) only once, after the second AsyncTask is completed.
Anyway, is there a reason why you use two AsyncTasks ? With your explanations we could believe that you might be able to use only one task.
I am doing a geocoding get request using AsyncTask which needs to finish executing, before proceeding to call another AsyncTask which will use the results from the geocoding request to make another call to another endpoint from the MainActivity.
I thought about forcing it to loop in a while using a "done" flag, set by the first AsyncTask, that may not even work however and it seems very hacky. Does anybody have an idea how to handle this?
AsyncTasks have the hook method onPostExecute(), where you can process its results.
From there, you can simply trigger any methods you want to be executed after the AsyncTask is finished.
For example:
protected void onPostExecute(Long yourResult) {
processYourResult(yourResult);
// Method startMoreLogic() will be executed after the AsyncTask is finished.
startMoreLogic();
}
make your asynctask as a private class and put everything that wait for result at onPoseExecute().
Or add .get() to the method where you call your asynctask.
I am working on app that updates data for every 8 secs and the update was done using Async task. I am using loops to achieve this condition
while(const_val > update_val) {
new Asynctask().execute();
Thread.sleep(8000);
}
const_val will be constant and will be not be changed by any other methods.lets say this value will be 5.update_val will be updated and decremented when Asynctask is called and let's the value will be 10. So , the while loop executes until the condition is true and asynctask ,sleep are called .
When I use above while loop in a general method then UI gets locked and if I use the same loop in another asynctask there was an error saying "Only original thread that created a view hierarchy can touch its view "
You need to change your code to start the AsyncTask and have it provide an update via its onPostExecute() method. By calling Thread.sleep() you are sleeping the main thread (or UI thread) of your app, which is not good. You do not ever want to block the main thread. This article may help you better understand AsyncTask and threading in Android: http://po.st/Cei3m2
I don't think you should use a surrounding loop. Look at this example:
http://javatechig.com/android/progress-notification-in-android-example
the AsyncTask is a private inner class
the onPostExecute updates the UI with a message/cancels the load bar
This way you don't have to loop and the onCreate() can return instantly.
Question arising from my first attempt at using an Async object.
I have a main activity in which some TextViews have been created programmatically and added to a LinearLayout. Also a button, when this is clicked, an AsyncTask object is instantiated and results are obtained in the doInBackGround method. How should the result strings be transferred to the TextViews?
a) by calling the SetText methods of these TextViews from the onPostExecute method,
b) using intents and an onActivityResult method in the main activity
c) some other way (a clue would be nice!)
Thanks!
I would go for the AsyncTask option. I'm guessing that as you already have one in place, the obtaining results part that happens when you click the button takes time, so it's good design to have that in the doInBackground method of the AsyncTask.
Then you can call each TextView's setText(...) method in the onPostExecute method in your AsyncTask. Or, it's more suitable, you can update each view as you get the result by using the publishProgress(...) and onProgressUpdate(...) methods (see the AsyncTask documentation) during the background calculations, instead of having to wait until the end.
Just bear in mind that you can only call setText(...) from the onPreExecute, onProgressUpdate and onPostExecute methods, as (at least it seems this way from your explanation) the views have been created on the UI thread, so they can only be modified from that same thread, which those methods run on.
When using an AsyncTask, you can use the doInBackground method for processing, and the onPostExecute to update any UI changes. So, if you need to use an AsyncTask, I'd go for option A.
Make the TextViews private and define them in doInBackground, then you can just call the setText method in onPostExecute or as the last thing in doInBackground, but i would recommend onPostExecute.
I have an Activity that retrieves information from a remote server and displays it in a TableLayout.
The function that retrieves the information from the server has its own timeout, and exception is thrown when the timeout gets exceeded.
Now, when the activity is loaded, I want the function to be fired, and a progressDialog to be shown while the function works, and to be hided if the function is done working, or if a timeout exception was thrown.
The problem: I've put the code that do all the functionality described above in the onCreate() function. Nothing is shown on the emulator screen, since the onCreate() function hasn't finished running...
I've also tried to put the code in the onStart() function... same unwanted results...
I'm trying to avoid using of threads, because the functionality needs many variables that the thread will not has access to them...
How can i implement the wanted behavior??
Thanks.
Use AsyncTask with ProgressDialog bounded:
http://it-projects.spb.ru/?p=150&lang=en
Create a class implementing Runnable and put all your load logic in there. Call a function in the activity when finished (lets say onFinished(params...))
Create a UI Handler and get the handler to update UI in onFinished(params...)
Create a thread in onCreate and start it there to call your Runnable.