[Solved] NetworkOnMainThread Error


http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html.

NetworkOnMainThread occurs because you might me doing netowrk related operation on the main UI Thread. You have to make network related operation in the background thread and updata ui on the ui thread.

You can use a asycntask. http://developer.android.com/reference/android/os/AsyncTask.html

class TheTask extends AsyncTask<Void,Void,Void>
{
      protected void onPreExecute()
      {           super.onPreExecute();
                //display progressdialog.
      } 

       protected void doInBackground(Void ...params)
      {  
            //http request. do not update ui here

            return null;
      } 

       protected void onPostExecute(Void result)
      {     
                super.onPostExecute(result);
                //dismiss progressdialog.
                //update ui
      } 

 }

Use async taks if the network operation is for a short period.

Straight from the doc

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

You can consider an alternative to asynctask robospice.https://github.com/octo-online/robospice.

solved NetworkOnMainThread Error