user1254554
user1254554

Reputation: 203

android multithreading and network on main thread exception;

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:

  1. both operations have to be in worker thread
  2. both operations are going in cycle till activity is alive.
  3. 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?

Upvotes: 0

Views: 4264

Answers (3)

Benoit
Benoit

Reputation: 4599

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.

Upvotes: 0

Code Poet
Code Poet

Reputation: 11427

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/

Upvotes: 0

Victor Wong
Victor Wong

Reputation: 2486

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)
     }
}

Upvotes: 2

Related Questions