Quantcast
Channel: How can I fix 'android.os.NetworkOnMainThreadException'? - Stack Overflow
Viewing all articles
Browse latest Browse all 191

Answer by Vipul Prajapati for How do I fix 'android.os.NetworkOnMainThreadException'?

$
0
0

Do this in Background Thread using AsycTask

Java

class NetworkThread extends AsyncTask<String, Void, String> {

    protected Void doInBackground(String... arg0) {
        //Your implementation
    }

    protected void onPostExecute(String result) {
        // TODO: do something with the feed
    }
}

Call wherever you need

new NetworkThread().execute("Your URL here");

Kotlin

internal class MyNetworkTask : AsyncTask<String, Void, RSSFeed>() {

    override fun doInBackground(vararg urls: String): RSSFeed? {
        try {
             // download
             // prepare RSSFeeds
             return RSSFeeds
         } catch (e: Exception) {
            //handle exception
            return null
        }
    }

    override fun onPostExecute(feed: RSSFeed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

Call in kotlin

MyNetworkTask().execute(url)

Viewing all articles
Browse latest Browse all 191

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>