Vahag Chakhoyan
Vahag Chakhoyan

Reputation: 779

okHttp NetworkOnMainThreadException despite to new Thread

In android studio project I am using okhttp to send post requests.

public void sentRequest(.... ....) {

        RequestBody formBody = new FormBody.Builder().add("number", number).build();
        Request request = new Request.Builder().url(serverBase + API_numberAvailabilityCheck).post(formBody).build();
        call = client.newCall(request);

        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, Object> requestResult = new HashMap<>();
                try {
                    final Response response = call.execute();
                } 
                ...........
                ...........
            }
        }).run();

}

But it throws an NetworkOnMainThreadException exception on line where I am calling final Response response = call.execute(); despite to new Thread. Why it's throwing like exception? And how to fix that?

Upvotes: 0

Views: 490

Answers (2)

SpiritCrusher
SpiritCrusher

Reputation: 21073

You have made a huge mistake here ..

new Thread(new Runnable() {
        @Override
        public void run() {

        }
    }).run();

You should call start() on thread to start not run() .. If you call run() directly then There will be No thread running and Your Thread will just act like a normal java class with a normal method run()..

You should be using

new Thread(new Runnable() {
    @Override
    public void run() {

    }
}).start();

On a side note a better approach to networking in android you should be using Retrofit .. Its way too easy to use and it also uses OkHttp under the hood.. And you do not have to worry about creating thread anymore..

Upvotes: 2

Gabriele Mariotti
Gabriele Mariotti

Reputation: 365048

The error is

thread.run() instead of thread.start().

Calling the run() method the code is running in the same thread, without starting new thread.

Upvotes: 3

Related Questions