Avatar ·

How to fix android.os.NetworkOnMainThreadException error in Android?

Hello everyone. I'm a beginner Android developer, writing a simple app that should receive data from a server via HTTP and display it in a TextView. But when I run the app, it crashes with the error `android.os.NetworkOnMainThreadException`. \n\nHere's my code:\n\n```java\npublic class MainActivity extends AppCompatActivity {\n private TextView textView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n\n // Trying to get data from the server\n try {\n URL url = new URL("https://api.example.com/data");\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n conn