0

I am connecting to a web service using

   urlConnection.connect();

This works only in AsyncTask. I am not able to execute the above statement on plain activity (without AsyncTask )

Is it the behavior by design, or I am missing something.

By the way, this is my first question

  • 2
    check out here http://stackoverflow.com/questions/15496278/httpurlconnection-is-throwing-exception – Rustam Aug 22 '15 at 08:31
  • I am not sure about android, but I know for sure that connecting with Web service must be in separate `threat`. Otherwise you can get blocked `UI` which is runned in the main `threat` – Bogdan Bogdanov Aug 22 '15 at 08:37
  • If you dont't want implement AsyncTask, you should try Volley libary instead, which is easy to learn and helpful. Happy coding :-) – BNK Aug 22 '15 at 08:45

2 Answers2

2

Welcome to stackoverflow. please use google search and stackoverflow search before posting a question. the chnaces are big, that someone else had already asked your question. stackoverflow rules

Network communications must be done in seprate Thread in android. Read more about it here developer wiki

Community
  • 1
  • 1
arash javanmard
  • 1,362
  • 2
  • 17
  • 37
2

To avoid creating an unresponsive UI, don't perform network operations on the UI thread.

You are possibly getting:

NetworkOnMainThreadException

because you are trying to perform network operation on Main UI Thread and thus overwhelming it. Instead use an AsyncTask.

Also, note that if the server is taking much time to respond, the main thread becomes unresponsive too.

Refer Android Doc for Developers for more information on this.

TryinHard
  • 4,078
  • 3
  • 28
  • 54