Appearance
How can I fix 'android.os.NetworkOnMainThreadException'?
The android.os.NetworkOnMainThreadException is a runtime exception that is thrown when an application attempts to perform a networking operation on the main thread. This is not allowed because networking operations can be slow and block the main thread, causing the UI to become unresponsive.
To fix this exception, you need to perform the networking operation in a background thread, rather than on the main thread. You can use a Thread, a HandlerThread, or an ExecutorService to perform the operation in the background.
Here's an example of how you can use an ExecutorService to perform a networking operation in the background:
java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NetworkExample {
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
public void fetchData() {
executor.execute(() -> {
try {
URL url = new URL("https://example.com/api/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Process response here, then update UI on the main thread
} catch (Exception e) {
e.printStackTrace();
}
});
}
}This code creates an ExecutorService and executes the networking task in the background. The try-catch block handles any exceptions that might be thrown during the connection or data reading process.
Note that after fetching the data, you must switch back to the main thread to update the UI, as background threads cannot directly modify Android views.
I hope this helps! Let me know if you have any other questions.