Error NetworkOnMainThreadException

0

asked by anonymous 26.11.2014 / 06:44

2 answers

2

This exception occurs, as I say very well, when attempting to perform a network operation on the main Thread. You need to run your code in AsyncTask :

class RetrieveFeedTask extends AsyncTask<String, Void, RssReader> {

    private Exception exception;

    protected RssReader doInBackground(String... urls) {
        try {
            SAXParserFactory factory =SAXParserFactory.newInstance();
            SAXParser saxParser=factory.newSAXParser();
            XmlParseHandler handler = new XmlParseHandler();
            saxParser.parse(urls[0], handler);
            saveInBD(handler.getItems());

        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(RssReader reader) {

    }
}

Instead of

RssReader reader = new RssReader("endereco.xml");

run the task:

new RetrieveFeedTask().execute(urlToRssFeed);

Do not forget to add this to AndroidManifest.xml :

<uses-permission android:name="android.permission.INTERNET"/>

SOen Source

Example

    
26.11.2014 / 10:05
0

I was having the same problem, I just implemented this on the onCreate method and it ran normally

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
    
30.11.2014 / 22:47