Android OS on network main thread exception

281 views Asked by At

I am working on an android application which connect with an asp.net web service.. for that when I tested the application is showing response

Android OS on network main thread exception".

My Code

class GetDetails extends AsyncTask<String, String, String>
{
  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Loading the result... Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
  }

  @Override
  protected String doInBackground(String... args)
  {
     try
     {
       runOnUiThread(new Runnable() {  
         @Override
         public void run() 
         {
           TextView webserviceResponse = (TextView) findViewById(R.id.textView1);
           webserviceResponse.setText("Requesting to server .....");

           //Create Webservice class object
           WebserviceCall com = new WebserviceCall(); 

           // Initialize variables
           String weight   = "18000";
           String fromUnit = "Grams";
           String toUnit   = "Kilograms";

           //Call Webservice class method and pass values and get response
           String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);   

           //Alert message to show webservice response
           Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms", 
           Toast.LENGTH_LONG).show();

           Log.i("AndroidExampleOutput", "----"+aResponse);

           webserviceResponse.setText("Response : "+aResponse);
         }
       }
       );
     }

     finally  {
     }
     return null;
   }
}


protected void onPostExecute(String file_url) {
  // dismiss the dialog once got all details
  pDialog.dismiss();
}

}
3

There are 3 answers

0
Ashish Patil On

Hi Use Handler to Update UI. Handler Example

private Handler handler = new Handler(new Handler.Callback() {  @Override public boolean handleMessage(Message msg) {
    switch( msg.what ){
                case MSG:                       
                    progressDialog.show();
                    break;
                case DETACH:
                    progressDialog.dismiss();
                    break;  
            }
    return false; } });

Call In Do In Background

Message m=Message.obtain();
 prepareMessage(m);
 handler.sendMessage(m);
public void prepareMessage(Message m)
    {
       Bundle b = new Bundle();
       b.putString("message", "Activity Done in background!!!!!!!");
       m.setData(b);

    }
2
M D On

Move your all code from runOnUiThread(new Runnable() {...} to doInBackground(...)

As runOnUiThread(..) code execute in main thread

also initialized your Views in Activity onCreate(..)

Correct:

class GetDetails extends AsyncTask<String, String, String>
{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading the result... Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

     @Override
     protected String doInBackground(String... args)
     {
         try
         {
                  webserviceResponse.setText("Requesting to server .....");

                  //Create Webservice class object
                   WebserviceCall com = new WebserviceCall(); 

                          // Initialize variables
                          String weight   = "18000";
                          String fromUnit = "Grams";
                          String toUnit   = "Kilograms";

                          //Call Webservice class method and pass values and get response
                          String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);                                

                          Log.i("AndroidExampleOutput", "----"+aResponse);

                         return aResponse;
                }

         }
        return null;
        }
     }

        protected void onPostExecute(String aResponse) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
           //Alert message to show webservice response
            Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms", 
                            Toast.LENGTH_LONG).show();
            webserviceResponse.setText("Response : "+aResponse);
        }
}
2
Akash On

Inside doInBackground() you have written a runonUiThread() method.

And inside that runOnUIThread() you are trying to make network call.That is why it is giving NetworkOnMainThreadException.

Put that network call outside runOnUiThread() String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit); but inside doInBackground() I hope it ll work.