0

I'm trying to send a Json object to a server with android studio, using okhttp3, and my app always crashes when I just try to send the json, when the app says the message was sent. In addition, I need to see in response my own json I created as a confirmation that my Json worked.

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
void post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    okhttp3.Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
            Log.e("TAG", "Failed sending message!");
            Toast.makeText(MainActivity.this,"Failed sending message",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onResponse(okhttp3.Call call, Response response) throws IOException {
            Log.d("TAG", "Message sent successfully!");
            Log.d("TAG", response.body().string());
            Toast.makeText(MainActivity.this,"Message sent successfully!",Toast.LENGTH_LONG).show();

        }
    });
}

My problem seems to appear in the onResponse and onFaliure functions. Here is the error I get on the variables I put in these functions: http://prntscr.com/i0dhgi

The error appears on all 4 variables, two in onFaliure and two in onResponse

Eli Kozinets
  • 117
  • 1
  • 9
  • Note that the screenshot you linked shows a **warning** not an error. You would not be able to install your app to a device if it were an error. – Code-Apprentice Jan 14 '18 at 19:13
  • See http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this for some tips on how to figure out the cause of the crash. – Code-Apprentice Jan 14 '18 at 19:14

1 Answers1

0

I ran your code on my machine what you need to do is something like that but make sure you have this in you app's build.gradle compile 'com.android.support:support-annotations:20.0.0' if you are using old android studio version. new versions make project with builtin annotation processor

 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    void post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure( @NonNull okhttp3.Call call,@NonNull  IOException e) {
                Log.e("TAG", "Failed sending message!");
//using a toast means updating the UI thread from back thread you have to call Content.runOnUiThread(new Runnable) to sync with the UI thread.
                //Toast.makeText(MainActivity.this,"Failed sending message",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(@NonNull okhttp3.Call call,@NonNull  Response response) throws IOException {
                Log.d("TAG", "Message sent successfully!");
                Log.d("TAG", response.body().string());
                //Toast.makeText(MainActivity.this,"Message sent successfully!",Toast.LENGTH_LONG).show();

            }
        });
    }

take a look at the picture I ran the code with dummy values and got to see the logcat clearly saying about thread handling issue! enter image description here

here is the final solution for you that I made will do the trick NOTE! you can replace "MainActivity.this" with your local Context

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
void post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    okhttp3.Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure( @NonNull okhttp3.Call call,@NonNull  IOException e) {
            MyActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
           //Handle UI here                        
        // Toast anything you like here//                
        }
    });
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call,@NonNull  Response response) throws IOException {
              MyActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
           //Handle UI here                        
          //happy on Response Toast here                
        }
    });
        }

        }
    });
}
Rizwan Atta
  • 3,222
  • 2
  • 19
  • 31
  • yes give it a try on your system adding annotation of NonNull will help for all params in the overriden methods – Rizwan Atta Jan 14 '18 at 19:13
  • @EliKozinets accept the answer if it worked for you or get in touch to discuss further – Rizwan Atta Jan 14 '18 at 20:54
  • using volley or Retrofit is also a nice solution for such issues like getting data response from urls in JSON and then parsing it out using GSON or manually ! it can save you from a lot of trouble like the one you are having right now!. – Rizwan Atta Jan 14 '18 at 20:56
  • Well, now I get my desired result but the app still crashes after I receive the data from the server. – Eli Kozinets Jan 14 '18 at 21:33
  • what does the logCat say now about the Toast. lemme guess It should be something related to backThread updating the UI Thread issue if it makes a crash on toast! in the overRidden method. – Rizwan Atta Jan 15 '18 at 01:19
  • in Volley's case I get to overRide on Error and on Response methods too but they get there calls after RequestQeue Executes them and they get to update my main thread with no issue. Simply put TOAST goes smooth in that case with no issue at all.. better share your LogCat result for the crash – Rizwan Atta Jan 15 '18 at 01:21
  • I just added the code you suggested, app finally doesn't crash :) Thanks a lot ! – Eli Kozinets Jan 15 '18 at 08:29
  • I am happy that it helped – Rizwan Atta Jan 15 '18 at 10:05