-4

I have no idea how to use threads; I was only trying to learn how to make a simple android program, but I'm trying to use an api and I get a NetworkOnMainThread exception. I read that it means I need to put my httpUrlConnection in a background thread (which doInBackground apparently might be helpful for), but I'm having trouble with tutorials on the internet.

I have a method right now called getResults that takes in a string and returns a list. Is there an easy way to adapt doInBackground so that I don't have to change my method?

An example of how to do so using doInBackground (or any other method) would be nice.

  • 2
    See the Android Guide for network operations, it explains where to put the code that makes network calls: http://developer.android.com/training/basics/network-ops/connecting.html – ESala Oct 18 '15 at 22:15

1 Answers1

0

There is a lot of information about these issues in the web, just google it.

Generally when you want to run network requests you should do it in another thread, and not you UI thread. AsyncTask is one of the more common ways to achieve that.

An example from Android Developers

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     //this is the place for the long background work
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     //If needed here you can update the UI about the progress.
 }

 protected void onPostExecute(Long result) {
     //Here you can update the UI
 }

}

You should also read Connecting to the Network as Darkean commented.

This is also very recommended Android background processing with Handlers, AsyncTask and Loaders - Tutoriall

SuperFrog
  • 7,631
  • 9
  • 51
  • 81