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
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
Why do I get android.os.NetworkOnMainThreadException when I run the class on a separate thread (implementing Runnable)?
In the else
part, you are calling run
methods directly which will execute the network call on mail thread, hence the exception
// this method is being called in onResume so
// second time, mQueueWorkerThread.run will be executed on main thread
private void startQueueWorkerThread(){
if (mQueueWorkerThread == null){
mQueueWorkerThread = new QueueWorkerThread(mContext,this, this);
new Thread(mQueueWorkerThread).start();
} else {
mQueueWorkerThread.makeReady();
mQueueWorkerThread.run(); // it will cause the exception
// new Thread(mQueueWorkerThread).start(); should use this
}
}
android.os.NetworkOnMainThreadException Exception
you are not suppose to do network operations on the ui/Main thread i know you are using async task but this is why you get the error look at your code here
getActivity().runOnUiThread(new Runnable() {public void run() {});
this makes it run on the ui thread despite async task beauty.. i'd suggest you remove this code and let async task work and use postexecute to post to the ui thread..
how do i fix FATAL EXCEPTION:main android.os.NetworkOnMainThreadException
The issue is that inside the AsyncTask's onPostExecute you call the following:
socket.getOutputStream()
This happens on the MainThread and therefore the exception is thrown. Move it to the doInBackground
inside the try catch block
so it looks like this:
public class ConnectPhoneTask extends AsyncTask<String,Void,Boolean> {
@Override
protected Boolean doInBackground(String... params) {
boolean result = true;
try {
InetAddress serverAddr = InetAddress.getByName(params[0]);
socket = new Socket(serverAddr, Constants.SERVER_PORT);//Open socket on server IP and port
if(isConnected) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true); //create output stream to send data to server
}
} catch (IOException e) {
Log.e("remotedroid", "Error while connecting", e);
result = false;
}
return result;
}
@Override
protected void onPostExecute(Boolean result)
{
isConnected = result;
Toast.makeText(context,isConnected?"Connected to server!":"Error while connecting",Toast.LENGTH_LONG).show();
}
}
Android.OS.NetworkOnMainThreadException in
FindInBackground's done callback method runs on UI thread and not on the async thread
Related Topics
How to Update Gradle in Android Studio
Recyclerview Inside Scrollview Is Not Working
Java.Util.Zip.Zipexception: Duplicate Entry During Packagealldebugclassesformultidex
Android Getresources().Getdrawable() Deprecated API 22
Difference Between Match_Parent and Fill_Parent
Detect Application Heap Size in Android
How to Change Theme For Alertdialog
How to Convert an Image into a Base64 String
Environment.Getexternalstoragedirectory() Deprecated in API Level 29 Java
How to Support Different Screen Size in Android
Horizontalscrollview Within Scrollview Touch Handling
Install_Failed_No_Matching_Abis When Install Apk
Why 'Pageradapter::Notifydatasetchanged' Is Not Updating the View
Illegalstateexception: Can Not Perform This Action After Onsaveinstancestate With Viewpager
What Is the Main Purpose of Settag() Gettag() Methods of View