Skip to content Skip to sidebar Skip to footer

Networkonmainthread Error

Hi everyone am trying to retrieve product information from my MSQL database. The price and title does work to get however not the image. I keep getting the NetworkOnMainThread erro

Solution 1:

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

classTheTaskextendsAsyncTask<Void,Void,Void>
{
      protectedvoidonPreExecute()
      {           super.onPreExecute();
                //display progressdialog.
      } 

       protectedvoiddoInBackground(Void ...params)
      {  
            //http request. do not update ui herereturnnull;
      } 

       protectedvoidonPostExecute(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.

Solution 2:

Take a look at AsyncTask() or, better, AsyncTaskLoader(). You have fine Java code in your question, but Android is a little different.

Post a Comment for "Networkonmainthread Error"