Networkonmainthread

How can I fix 'android.os.NetworkOnMainThreadException'?

NOTE : AsyncTask was deprecated in API level 30.

AsyncTask | Android Developers

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

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

private Exception exception;

protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
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();
} catch (Exception e) {
this.exception = e;

return null;
} finally {
is.close();
}
}

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

How to execute the task:

In MainActivity.java file you can add this line within your oncreate() method

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

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

Android - android.os.NetworkOnMainThreadException

NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.

You should call sendfeedback method on asynctask then only above code will work. As webserver is taking lot of time to response main thread becomes unresponsive. To avoid it you should call it on another thread. Hence asynctask is better.

here is link that illustrates how to use asynctask

NetworkOnMainThread

Any idea why?

Because, if that hunk of code is being executed on the main application thread, you are doing network I/O on the main application thread.

I've read I might need to implement asynctask but im new to it and not sure what parts need their own thread.

I would put the network I/O and the parsing in doInBackground() and the setListAdapter() call in onPostExecute() of an AsyncTask.

How to fix android.os.NetworkOnMainThread

You need to run network related tasks on another thread, something like this:

Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Put your code that you want to run in here
} catch (Exception e) {
e.printStackTrace();
}
}

Now, if you are not sure what causing this you can check your error log, it will guid you to the line that caused this problem.

Another thing that you can do is to add custom logs/prints with the error description, later on, you can check those logs to see if any of them called (if yes this means that you were getting error)

android.os.NetworkOnMainThreadException while posting data to url

Its because you're doing network operation on Main UI thread

if you're using threads to do network operations
then you can use this code snippet

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

in your OnCreate()

But its wrong practice to use above said operation, instead you should use AsyncTask class provided by android to handle properly network operation without blocking UI thread.

you can learn more by visiting this LINK

or can use the below code

private class UploadFiles extends AsyncTask<String, Void, Void> {
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}

protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}

protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}

and you can simple call this class by writing

 new UploadFiles ().execute(new String[]{//YOUR LINK});

Android HttpClient : NetworkOnMainThreadException

On ICS and later you cannot do network operations on the UI thread anymore. Instead you are forced to create a new thread and do your networking stuff there.

Possible tools are Android's AsyncTask and the normal Java Thread.

A good tutorial can be found here: Android Threads, Handlers and AsyncTask - Tutorial

How to fix NetworkonMainThreadException in Android?

Your Exception actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.

Your code that connects to the url should be executed for example inside an AsyncTasks doInBackground() method, off the UI-Thread.

Take a look at this question on how to use the AsyncTask: How to use AsyncTask



Related Topics



Leave a reply



Submit