2

I am using Kevin Sawicki's library for HTTP requests in my Android application. The actual call to the library methods for making the request is made in a class file (it's not called from an activity) called TemplateHelper. The method that calls the HttpRequest library in my TemplateHelper class looks like this

public static JSONObject GetTemplates() {
    try {
        return new JSONObject(HttpRequest.get("http://myapi.mycompany.com/templates").body());
    } catch (HttpRequestException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From my activity i then call TemplateHelper.GetTemplates() to get the data. However, when i do this Android throws the exception android.os.NetworkOnMainThreadException. A quick Google search shows me the code for running the HTTPRequest on a separate thread. But if i run the code in a separate thread, how can i return the result to the main thread?

Anton Gildebrand
  • 3,641
  • 12
  • 50
  • 86
  • 1
    Don't. Use asynchronous flow. – Sotirios Delimanolis Oct 11 '13 at 17:04
  • 2
    If you will use `AsyncTask`, `onPostExecute()` method will be run on the main thread after task finished. – SpongeBobFan Oct 11 '13 at 17:07
  • [This answer](http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask/18517648#18517648) will show you how to implement an `interface` with `AsyncTask` so you can get a `callBack` to the `MainActivity` when your task has finished. – codeMagic Oct 11 '13 at 17:17

2 Answers2

4

You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask or you need to create a new thread. Personally, I'd use AsyncTask. When you use AsyncTask you can use the onPostExecute method to return the value to the main thread.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
0

Create a Async Task in yout TemplateHelper class, Async task runs in a different thread so main thread exception will not be there

Check this tutorial, this is exactly you need to do.

Jitender Dev
  • 6,907
  • 2
  • 24
  • 35