Peltier Cooler
Peltier Cooler

Reputation: 169

Using Async for a Network activity

I understand that network tasks should be done in an Async thread, and I think my code is inside one, but I still get the error

.MainActivity}: android.os.NetworkOnMainThreadException

which confuses me, since pretty much everything is inside an Async task:

    public void onStart() {
        super.onStart();
        new GetRssFeedTask().execute();
    }

The rest of the code is inside the Async task:

  private class GetRssFeedTask extends AsyncTask<Void, Void, List<String>> {
        private String getRssFeed() throws IOException {
            InputStream in = null;
            String rssFeed = null;
            try {
                URL url = new URL("http://stuffilikenet.wordpress.com/feed/main.xml");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                for (int count; (count = in.read(buffer)) != -1; ) {
                    out.write(buffer, 0, count);
                }
                byte[] response = out.toByteArray();
                rssFeed = new String(response, "UTF-8");
            } finally {
                if (in != null) {
                    in.close();
                }
            }
            return rssFeed;
        }      

  ...rest of code (seriously)...
  }

Where should I look for my error?

Upvotes: 1

Views: 466

Answers (2)

Manish Menaria
Manish Menaria

Reputation: 27511

network tasks should be done in an doInBackground() .

doInBackground() callback method runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI.

  • perform initilization in onPreExecute() method
  • perform background task in doInBackground() method
  • update the UI in onPostExecute() method

    public class MyAyncTask extends AsyncTask<Void, Void, Void> {
    
    @Override
    protected void onPreExecute() {
        //Here you can show progress bar or something on the similar lines.
        //Since you are in a UI thread here.
        super.onPreExecute();
    }
    
    @Override
    protected Void doInBackground(Void... params) {
        // Here you are in the worker thread and you are not allowed to access UI thread from here
        //Here you can perform network operations or any heavy operations you want.
        return null;
    }
    
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        //After completing execution of given task , control will return here.
        //Hence if you want to populate UI elements with fetched data, do it here
    }
    
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // You can track you progress update here
    }
    
    }
    

Upvotes: 4

earthw0rmjim
earthw0rmjim

Reputation: 19427

It is not enough to do define the network operations inside your AsyncTask class to run them on a background Thread.

You have to execute them inside doInBackgrund().

You need to override doInBackground() inside your AsyncTask class and perform your network operations there.

@Override
protected Void doInBackground(Void... params) {
    // here
    return null;
}

Upvotes: 2

Related Questions