How to fix 'android.os.NetworkOnMainThreadExce

2020-01-22 09:35发布

I got an error while running my Android project for RssReader.

Code:

URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();

And it shows the below error:

android.os.NetworkOnMainThreadException

How can I fix this issue?

30条回答
老娘就宠你
2楼-- · 2020-01-22 10:11
  1. Do not use strictMode (only in debug mode)
  2. Do not change SDK version
  3. Do not use a separate thread

Use Service or AsyncTask

See also Stack Overflow question:

android.os.NetworkOnMainThreadException sending an email from Android

查看更多
成全新的幸福
3楼-- · 2020-01-22 10:11

The top answer of spektom works perfect.

If you are writing the AsyncTask inline and not extending as a class, and on top of this, if there is a need to get a response out of the AsyncTask, one can use the get() method as below.

RSSFeed feed = new RetreiveFeedTask().execute(urlToRssFeed).get();

(From his example.)

查看更多
倾城 Initia
4楼-- · 2020-01-22 10:12

Although above there is a huge solution pool, no one mentioned com.koushikdutta.ion: https://github.com/koush/ion

It's also asynchronous and very simple to use:

Ion.with(context)
.load("http://example.com/thing.json")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});
查看更多
在下西门庆
5楼-- · 2020-01-22 10:13

Do the network actions on another thread

For Example:

new Thread(new Runnable(){
    @Override
    public void run() {
        // Do network action in this function
    }
}).start();

And add this to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
查看更多
何必那么认真
6楼-- · 2020-01-22 10:14

You disable the strict mode using following code:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

This is not recommended: use the AsyncTask interface.

Full code for both the methods

查看更多
【Aperson】
7楼-- · 2020-01-22 10:15

I solved this problem using a new Thread.

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 
查看更多
登录 后发表回答