How to fix android.os.NetworkOnMainThreadException in Android?
Hi everyone! I'm a beginner Android developer, writing a simple app that loads data from a server via HTTP. I have an Activity where I call a method to get JSON from the API. The code looks like this:
```java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = loadDataFromApi(); // Network request call
TextView textView = findViewById(R.id.textView);
textView.setText(result);
}
private String loadDataFromApi() {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnecti
No answers yet.
Log in to leave an answer