T
T
thatmaniscool2022-01-11 12:01:19
Java
thatmaniscool, 2022-01-11 12:01:19

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());
    }

But when it calls a static method to create an array of data, an exception immediately occurs:
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

1 answer(s)
N
Nikolay Savelyev, 2022-01-11
@thatmaniscool

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 question

Ask a Question

731 491 924 answers to any question