Answer the question
In order to leave comments, you need to log in
How to resolve android.os.NetworkOnMainThreadException?
When developing the application, I encountered the android.os.NetworkOnMainThreadException exception, while everything works fine on tests, the data is downloaded correctly.
What I did:
1. Added the permission to the manifest
2. Tested the code:
@Test
public void checkCorrectURL() {
int code = Utils.getCodeResponse("https://mail.ru");
assertEquals(200, code);
}
@Test
public void readJsonFromURL() {
String json = Utils.readJsonFromURL("https://api.github.com/users");
System.out.println(json);
}
@Test
public void isJSONValid() {
boolean isValid = Utils.isJSONValid(jsonString);
boolean isNotValid = Utils.isJSONValid("this json string is not valid!");
assertTrue(isValid);
assertFalse(isNotValid);
}
@Test
public void checkValidURLImage() {
String correctLink = "https://avatars.githubusercontent.com/u/2?v=4";
String incorrectLink = "https://avatars.githubusercntent.com/u/?v=4";
int code1 = Utils.getCodeResponse(correctLink);
int code2 = Utils.getCodeResponse(incorrectLink);
assertEquals(200, code1);
assertNotEquals(200, code2);
}
@Test
public void createItemsList() {
List<Data> users = Utils.createItemList(WhoIs.USER, "https://api.github.com/users");
List<Data> teams = Utils.createItemList(WhoIs.TEAM, "https://api.github.com/organizations");
assertNotNull(users);
assertNotNull(teams);
for (Data data : users)
System.out.println(data.toString());
for (Data data : teams)
System.out.println(data.toString());
}
List <Data> items = Utils.createItemList(WhoIs.USER, "https://api.github.com/users");
Answer the question
In order to leave comments, you need to log in
In Android, it is forbidden to work with the network in the main UI thread, which is what the error says.
Take out work with a network in a separate flow. Rx or coroutines to help you
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question