1

My problem is that when response is successful, i am getting response. But if response is not success, I am not getting any response in body, it's null. In case of any error like 404, 500 response is null. I am a beginner.

enter image description here

void sendMessage(){
    String user_id = sessionManager.getPreferences(getActivity(), "user_id");
    String message = binding.inputMessage.getText().toString();
    String api_key = "954f011a-ab85-42e";
    String secret_key = "v7FTQC&Cppbukk";
    if (message.isEmpty()){
        binding.inputMessage.setError("Please write your message");
        binding.inputMessage.requestFocus();
    }else {
        binding.inputMessage.setError(null);

        APIService service = RetrofitInstance.getRetrofitInstance().create(APIService.class);
        Call<ContactUsModel> call = service.sendMessage(user_id, message, api_key, secret_key);
        progressDialog.setMessage("Sending");
        progressDialog.show();
        call.enqueue(new Callback<ContactUsModel>() {
            @Override
            public void onResponse(Call<ContactUsModel> call, Response<ContactUsModel> response) {
                progressDialog.dismiss();
                ContactUsModel model = response.body();
                if (response.code() == 201){
                    if (model.getSuccess() == 1){
                        binding.inputMessage.setText("");
                        Toast.makeText(getActivity(), model.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                }else{
                   //Toast.makeText(getActivity(), response.body().toString(), Toast.LENGTH_SHORT).show();
                    Log.e("responcebody" , response.body().toString());
                }

            }

            @Override
            public void onFailure(Call<ContactUsModel> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }
}

My Model is below in which i am getting responce, parameters name are totally correct

            package com.example.miinterest.model;
        
        import com.google.gson.annotations.SerializedName;
        
        public class ContactUsModel {
            @SerializedName("success") private int success;
            @SerializedName("message") private String message;
        
            public int getSuccess() {
                return success;
            }
        
            public void setSuccess(int success) {
                this.success = success;
            }
        
            public String getMessage() {
                return message;
            }
        
            public void setMessage(String message) {
                this.message = message;
            }
        }

And Api Call Method. I created a method and calling API from here

               @FormUrlEncoded
            @POST("addContactUsQuery")
            Call<ContactUsModel> sendMessage(
                    @Field("user_id") String user_id,
                    @Field("message") String message,
                    @Header("api_key") String api_key,
                    @Header("secret_key") String secret_key
            );
Rakesh Saini
  • 660
  • 2
  • 7
  • 20
  • 1
    Actually, you don't get the null. Log the response.errorBody().toString(). You will get the output in case of 404,500 – Tausif Jun 01 '21 at 12:04
  • Please add the server response that your receive also you need to check if the api call was successfully of not. if (response.isSuccessful()) {} else { } – ben khedher mahmoud Jun 01 '21 at 12:05
  • when i change response.body.toString to response.errorBody().toString(). Then i am getting "okhttp3.ResponseBody$1@59bbee6" Error. I also included response.isSuccessfull(). – Rakesh Saini Jun 01 '21 at 12:19
  • @Rakesh saini convert the response to jsonObject and display it put this 2 lines of codes inside try, catch block JSONObject jsonError = new JSONObject(response.errorBody().string()); Log.e("error", jsonError.toString()); – ben khedher mahmoud Jun 02 '21 at 09:44
  • Thanks for reply, i applied your code but still getting null in "jsonError " – Rakesh Saini Jun 02 '21 at 12:08
  • Please @Rakesh show me the log – ben khedher mahmoud Jun 02 '21 at 12:59
  • I am getting following error -> i also updated screenshot in my question above please see the pic also -- > java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference – Rakesh Saini Jun 02 '21 at 16:53
  • @Rakesh response.isSuccessuful() returns true if code() is in the range [200..300) so please check the endpoint name is correct and if you web server intercept the request and send response – ben khedher mahmoud Jun 03 '21 at 09:39
  • Same API i am using in flutter but there its working fine, I also check your statement. But not solution. – Rakesh Saini Jun 03 '21 at 10:53

1 Answers1

1

It is not .toString() but is .string(). You should return your errorBody as response.errorBody().string(). Please refer here

How to get response as String using retrofit without using GSON or any other library in android

Teo
  • 876
  • 9
  • 22