0

Ok, I have read a lot of questions here on StackOverflow but i still can't understand so i'm opening a new question.

I made a class which function connects to internet and fetches json as string. It works fine in normal Java Application but i can't get it work in my android project.

I'm getting next error: android.os.NetworkOnMainThreadException

So to my understanding I have to use AsyncTask but I don't know how to wrap my function into it.

Function looks like this:

public static String get(String url){
  //connect and get data to string
  // return string
}

Like I said it works fine in normal JavaApplication but not in android project.

Thx for help!

3 Answers3

0

As I understand you use AndroidHttpClient -> so you can not even try to perform your network operations in the UI thread - > so create separate thread for this purpose. You can either use AsynchTask, Thread + Handler or HandlerThread for this purpose, or you can try to experiment here with java.util.concurrent package.

NetworkOnMainThreadException | Android Developers
developer.android.com/... - 
Class Overview. The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for ...
pvllnspk
  • 5,667
  • 12
  • 59
  • 97
  • if the activity class implements runnable, and if you do networking operations using the `run()` method of this thread + a handler, it still causes a `NetworkOnMainThreadException`, should the `Runnable` be dissociated from this activity ? – Jerec TheSith Jan 31 '13 at 13:16
0

http://developer.android.com/reference/android/os/AsyncTask.html Look at the sample

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
}

Your "get" function must be splitted into 2 separate function in this class

what you want to get in, put in

doInBackground

And what you want to do with data which you receive into

onPostExecute
Rad
  • 101
  • 1
  • 6
0

You can create the thread method which extends AsyncTask (as you correctly understood), and execute it with .execute().

Exactly how you set it up is up to you. Here's a link with a tutorial on spinning these threads: http://www.vogella.com/articles/AndroidPerformance/article.html#concurrency_threads

DRobinson
  • 4,441
  • 22
  • 31