0

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?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Vahag Chakhoyan
  • 873
  • 1
  • 10
  • 21
  • Possible duplicate of [How do I fix android.os.NetworkOnMainThreadException?](https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception) – a_local_nobody Aug 03 '19 at 11:11
  • 1
    OkHttp can handle threading for you. Use `enqueue()` instead of `execute()`. – CommonsWare Aug 03 '19 at 11:14

2 Answers2

3

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.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
2

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..

ADM
  • 20,406
  • 11
  • 52
  • 83