I am writing an android application where all my data is expose using web service. I am writing a wrapper class to fetch data from the services called DataManager.
public class DataManager{
public DataManager (){}
public String getValue ()
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet ("some url");
try
{
HttpResponse response = client.execute(get);
if (response.getStatusLine ().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity ();
String result = EntityUtils.toString(entity);
return result;
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
When I call this method a RuntimeException is generated on the UI thread. How can I refactor this
code and fetch the values from the webservice and return these values asynchronously. [NOTE] I am writing this for some team members so they can use it to get data from the service so I want it to be has easy has possible for them to use.
Use
AsyncTaskorIntentService. Doing networking (and in general lengthy operations) on UI thread is no-no on Android.Here you got with AsyncTask fundamentals and some tutorials
And here you got with IntentService fundamentals and tutorials
I’d use AsyncTask myself (IntentService’s jobs are queued), but be aware about change in the way it is handled in newer APIs. Not a big deal (just a few more code lines), though