Reputation: 4398
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?
Upvotes: 2
Views: 1104
Reputation: 34301
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();
Upvotes: 2
Reputation: 3268
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.
Upvotes: 1
Reputation: 8608
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.
Upvotes: 0