Search code examples
javaandroidexceptionandroid-asynctasknetworkonmainthread

Android:NetworkOnMainThreadException error inside AsyncTask


okay so i created a inner class which extends AsycTask in order for my code to run outwith the UI thread. However i'm getting this error so i assume this means some part of my onPostExecute needs to be done in doInBackground however i cant figure out exactly what this is

public class asyncTask extends AsyncTask<String, Integer, String> {

        ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);

        @Override
           protected void onPreExecute() {
          dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          dialog.setProgress(0);
          dialog.setMax(100);
          dialog.setMessage("loading...");
          dialog.show();
           }

         @Override
           protected String doInBackground(String...parmans){
                {

                    for(int i = 0; i < 100; i++){


                        publishProgress(1);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }


                    String urlString = petrolPriceURL;
                    String result = "";
                    InputStream anInStream = null;
                    int response = -1;
                    URL url = null;

                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        return null;
                    }
                    URLConnection conn = null;
                    try {
                        conn = url.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        return null;
                    }

                    // Check that the connection can be opened
                    if (!(conn instanceof HttpURLConnection))
                        try {
                            throw new IOException("Not an HTTP connection");
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            return null;
                        }
                    try
                    {
                        // Open connection
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setAllowUserInteraction(false);
                        httpConn.setInstanceFollowRedirects(true);
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();
                        response = httpConn.getResponseCode();
                        // Check that connection is OK
                        if (response == HttpURLConnection.HTTP_OK)
                        {
                            // Connection is OK so open a reader 
                            anInStream = httpConn.getInputStream();
                            InputStreamReader in= new InputStreamReader(anInStream);
                            BufferedReader bin= new BufferedReader(in);

                            // Read in the data from the RSS stream
                            String line = new String();
                            while (( (line = bin.readLine())) != null)
                            {
                                result = result + "\n" + line;
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                            try {
                                throw new IOException("Error connecting");
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                    }

            return result;

                }
           }
           @Override

           protected void onProgressUpdate(Integer...progress){

               dialog.incrementProgressBy(progress[0]);
           }

           @Override
           protected void onPostExecute(String result) {
               // Get the data from the RSS stream as a string

               errorText = (TextView)findViewById(R.id.error);
               response = (TextView)findViewById(R.id.title);

               try
                {
                    // Get the data from the RSS stream as a string
                    result =  doInBackground(petrolPriceURL);
                    response.setText(result);
                    Log.v(TAG, "index=" + result);
                }
                catch(Exception ae)
                {
                    // Handle error
                    errorText.setText("Error");
                    // Add error info to log for diagnostics
                    errorText.setText(ae.toString());
                } 
                if(dialog.getProgress() == dialog.getMax())
                dialog.dismiss();

           }
        }

if someone could point out my error as well as show an example of where the code is suppose to go in my doInBackground that would be great. Thanks


Solution

  • problem:

    result =  doInBackground(petrolPriceURL);
    

    you are implicitly calling the doInbackground method in the onPostExecute which will actually run in your UI thread instead on a different thread thus resulting to Android:NetworkOnMainThreadException.

    Also it is unnecessary to call doInBackground that it is already executed before onPostExecute when you execute your Asynctask. Just directly use the result parameter of the onPostExecute.

    sample:

    @Override
           protected void onPostExecute(String result) {
               // Get the data from the RSS stream as a string
    
               errorText = (TextView)findViewById(R.id.error);
               response = (TextView)findViewById(R.id.title);
    
                response.setText(result);
    
                if(dialog.getProgress() == dialog.getMax())
                dialog.dismiss();
    
           }