Search code examples
javaandroidandroid-asynctasknetworkonmainthread

NetworkOnMainThreadException inside AsyncTask.doInBackground() method


First encountered this while trying to do networking on the main UI thread. Then tried to avoid it with AsyncTask, but still getting the same Exception. Networkign is happening only inside AsyncTask.doInBackground() method. But I still get this exception. How do I fix this?

public class AsyncRSSLoader extends AsyncTask<Void, Void, RSSData> {
    private String url = "http://www.nasa.gov/rss/dyn/image_of_the_day.rss";


    @Override
    protected RSSData doInBackground(Void... params) {
        try {
            IotHandler handler = new IotHandler();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(handler);
            InputStream inputStream = new URL(url).openStream();
            reader.parse(new InputSource(inputStream));

            RSSData data = new RSSData();
            data.setDate(handler.getDate());
            data.setTitle(handler.getTitle());

            data.setImage(getBitmap(handler.getImageUrl()));

            return data;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("NASA_RSS", e.getStackTrace().toString());
        }

        return null;
    }

}

and the usage of this class:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AsyncRSSLoader loader = new AsyncRSSLoader();
        RSSData data = loader.doInBackground();

        resetDisplay(data.getTitle(), data.getDate(), data.getImage(), data.getDescription());
    }

Solution

  • you have to call

    loader.execute();
    

    instead of loader.doInBackground(). It is execute() that calls doInBackground from a working thread. If you need to pass data back to the Activity, use a delegate. You can find an example here