How to Handle Two Different Response in Retrofit
Asked Answered
U

6

11

I followed this to POST Data Using Retrofit2

I Used JSON POJO to Parse my POST and GET files

So Here If Data inside the Records Is there I will get This Kind of Response

{
"status": "200",
"response": [{
        "cnt_id": "201",
        "phn_no": "3251151515",
        "dat_cnt": "Reset Password request Said to Mail"
    },
    {
        "cnt_id": "209",
        "phn_no": "555465484684",
        "dat_cnt": "Hi DEMO User , Congratulations! Your account has been created successfully."
    },
    {
        "cnt_id": "210",
        "phn_no": "4774748",
        "dat_cnt": "Hi XYZ , Congratulations! Your account has been created successfully."
    }
]
}

If there is no Data I will get

{"status":"204","response":{"msg":"No Content"}} or
{"status":"400","response":{"msg":"BadRequest"}} or
{"status":"401","response":{"msg":"Unauthorized User"}}

So Here I can eable to Parse the data which is there in the status 200 but when Status is not equals to 200 I want to Handle them

I tried with

   status = response.body().getStatus();
   if(status.equals("200")) {
      List<Response> resList =  response.body(). getResponse();

            for(int i = 0; i<resList.size(); i++)
            {.
             .
              ..
             .
            }
        }

        else {
             //not Implemented
             }

now what should I write in Else I used response data in POJO which are not equals to 200 but I its asking for list

Update

com.example.Example.java

public class Example {
    @SerializedName("status") @Expose private String status;
    @SerializedName("response") @Expose private List<Response> response = null;
}        

com.example.Response.java

public class Response {
    @SerializedName("cnt_id") @Expose private String cntId;
    @SerializedName("phn_no") @Expose private String phnNo;
    @SerializedName("dat_cnt") @Expose private String datCnt;
}
Uphemia answered 9/7, 2018 at 4:13 Comment(2)
Can you please keep method of the Api call .Valence
Its there in that Example link codingsonata.com/retrofit-tutorial-android-part-2-post-requests... if you have similar data,,, come to chat I will giveContraband
V
15
public class Example {
    @SerializedName("status") @Expose private String status;
    @SerializedName("response") @Expose private Object response = null;
}

public class Response {
    @SerializedName("cnt_id") @Expose private String cntId;
    @SerializedName("phn_no") @Expose private String phnNo;
    @SerializedName("dat_cnt") @Expose private String datCnt;
}

public class ResponseError{
    @SerializedName("msg") @Expose private String msg;
}

And Your callBack methods should be like

new Callback<Example>() {
    @Override
    public void onResponse(Call<Example> call, Response<Example> response) {
       if (response.isSuccessful()){
          Example example = response.body();
          Gson gson = new GsonBuilder().create();

          if (example.status.equals("200")) {
              TypeToken<List<Response>> responseTypeToken = new TypeToken<List<Response>>() {};
              List<Response> responseList = gson.fromJson(gson.toJson(example.getResponse()), responseTypeToken.getType());
          } else {
              //If for everyOther Status the response is Object of ResponseError which contains msg.
              ResponseError responseError = gson.fromJson(gson.toJson(example.getResponse()), ResponseError.class);
          }
       }
    }
    
    @Override
    public void onFailure(Call<Example> call, Throwable t) {
        //Failure message
    }
}
Valence answered 9/7, 2018 at 4:50 Comment(10)
my I know How to use this ResponseError in Example classContraband
Than what's the problemValence
you have added this line @SerializedName("response") @Expose private String response = null; its fine.. Shall I need to add another for ResponseError?Contraband
If you have your own than it's fine. Don't create one. Use that only. If not than create. Else you'll not be able to parse the response from Gson.Valence
Actually What ever is there its calling List.. public List<Response> getResponse() { return response; } for non array List I need to add Response Error?Contraband
To check that we require your method structure.Valence
I have followed completely.. that tutorial code codingsonata.com/retrofit-tutorial-android-part-2-post-requestsContraband
Let us continue this discussion in chat.Valence
@RohitRawat What's your issue?Valence
Is there also a way for handling two different responses when using kotlins coroutines instead of callbacks?Slantwise
L
4

You can achieve this by fetching errorBody() with help of Retrofit2.

Make one POJO model class with name RestErrorResponse.java For handle this Response.

{"status":"401","response":{"msg":"Unauthorized User"}}

And follow information given below:

 if (response.isSuccessful()) {

        // Your Success response. 

 } else {

        // Your failure response. This will handles 400, 401, 500 etc. failure response code


         Gson gson = new Gson();
         RestErrorResponse errorResponse = gson.fromJson(response.errorBody().charStream(), RestErrorResponse.class);
                    if (errorResponse.getStatus() == 400) {
                        //DO Error Code specific handling

                        Global.showOkAlertWithMessage(YourClassName.this,
                                getString(R.string.app_name),
                                strError);

                    } else {
                        //DO GENERAL Error Code Specific handling
                    }
                }

I handled all failure response by this method. Hope this can also helps you.

Lacielacing answered 9/7, 2018 at 4:32 Comment(7)
actually I am using Example and Response class where should I update this {"status":"401","response":{"msg":"Unauthorized User"}} and what should be in else...?Contraband
@Don'tBenegative You need to create Seperate class to handle this error response.Lacielacing
Print log of response.errorBody().charStream() in else part of above code.Lacielacing
You are on the Right way. Replace "RestErrorResponse" with your "Example" class. and then get Your error message by errorResponse.getResponse().getMsg(). get it??Lacielacing
Shall I need to Create again two Class?Example =RestErrorResponse and Response=Response2?Contraband
whats that error. First Print log of "response.errorBody().charStream()" in else part of above code. And check that will you getting proper failure response here or not??Lacielacing
Let us continue this discussion in chat.Lacielacing
A
2
class Response<T> {
        private String status;
        private T response;

        private boolean isSuccess() {
            return status.equals("200");
        }
    }

    class ListData {
        private String cnt_id;
        private String phn_no;
        private String dat_cnt;
    }

    class Error {
        private String msg;
    }

    public class MainResponse {
        @SerializedName("Error")
        private Error error;
        @SerializedName("AuthenticateUserResponse")
        private List<ListData> listData;
    }

@POST("listData")
Call<Response<MainResponse>> listData();
Anthropologist answered 9/7, 2018 at 4:22 Comment(2)
hi user@user3235116 Once Check my Update and Can you suggest me where I need to changeContraband
Thanks for Answer ... can you suggest me In my code..?Contraband
Z
1

you can use different pojo class to handle error msg

status = response.body().getStatus();
if(status.equals("200")) {
    ResponseSuccess res =  response.body();
    for(int i = 0; i < res.response.size(); i++){
        Log.d("TAG", "Phone no. " + res.response.get(i).phn_no);
    }
} else {
    Converter<ResponseBody, ResponseError> converter = getRetrofitInstance().responseBodyConverter(ResponseError.class, new Annotation[0]);
    ResponseError error;
    try {
        error = converter.convert(response.errorBody());
        Log.e("TAG", error.response.msg);
    } catch (IOException e) {
        error = new ResponseError();
    }
}

success pojo class

public class ResponseSuccess {
    public String status;
    public List<Response> response;
    public class Response{
        public String cnt_id;
        public String phn_no;
        public String dat_cnt;
    }
}

error pojo class

public class ResponseError {
    public String status;
    public Response response;
    public class Response{
        public String msg;
    }
}
Zinovievsk answered 9/7, 2018 at 4:46 Comment(4)
Actually Before Response class I have status?,, So I Have Two class pastebin.com/raw/fQMFAUXW now I need to create 3rd class? I tried to add you code in Example or Response class I am facing errorsContraband
you can create single class for success and error like I have defined please checkZinovievsk
Hi @VinayRathod Now I have 3 calsses...MainResponse,ResponseSuccess,ResponseError but in Main Response what should I define in Main Response... I already Defined reesponse List in calls pastebin.com/raw/xB0Y7nmp.. So if there is no response what should I doContraband
you don't have to create MainResponse since it is cover in ResponseSuccess classZinovievsk
C
0

So in your case there is possibility of getting response tag type as String/List<Response>. so you declare response tag type as Object

@SerializedName("response") @Expose public Object response;

and write code in onResponse method of retrofit following code snippet

if (response.body().response!=null &&  response.body().response instanceof Collection<?>) {
            //if you find response type is collection then convert to json then json to real collection object
            String responseStr = new Gson().toJson(data.diagnosis.provisionalDiagnosis);
            Type type=new TypeToken<List<Response>>(){}.getType();
            List<Response> responseList=new Gson().fromJson(responseStr,type);
            if(responseList.size() > 0){
                binding.phoneTv.setText(responseList.get(0).phnNo);
            }
        }

I found this is easy way to handle single tag with multiple type

Carpophore answered 14/6, 2021 at 7:38 Comment(0)
S
0

You can try below code for response code 200, 401, 400

public void getMusicDetail(String path, String id) {
        if (AppUtil.isInternetAvailable(context)) {
            binding.loader.setVisibility(View.GONE);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("token", Prefs.getPrefInstance().getValue(context, Const.TOKEN, ""));
                jsonObject.put("song_id", id);
                jsonObject.put("menu_id", path);
            } catch (JSONException e) {
                binding.loader.setVisibility(View.GONE);
                e.printStackTrace();
            }
            String params = jsonObject.toString();
            final RequestBody get_music_detail = RequestBody.create(params, MediaType.parse("application/json"));
            APIUtils.getAPIService().get_now_playing(get_music_detail, "Tracks").enqueue(new Callback<MusicResponse>() {
                @Override
                public void onResponse(@NonNull Call<MusicResponse> call, @NonNull Response<MusicResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getStatus() != null && response.body().getStatus().equals(200)) {
                            if (response.body().getData() != null && !response.body().getData().isEmpty()) {
                                songs = response.body().getData();
                                binding.songPlayPauseNowPlaying.setSelected(!MediaController.getInstance().isAudioPaused());
                                Glide
                                        .with(Durisimo.applicationContext)
                                        .load(response.body().getData().get(0).getSongImage())
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .centerCrop()
                                        .placeholder(R.drawable.app_logo)
                                        .error(R.drawable.app_logo)
                                        .into(binding.assetImage);

                                binding.assetName.setText(response.body().getData().get(0).getSongName());
                                binding.assetArtist.setText(response.body().getData().get(0).getSongArtist());
                                binding.loader.setVisibility(View.GONE);

                                shareDetails = "Song Name: " + response.body().getData().get(0).getSongName() + "\n\n" + "Song URL: " + response.body().getData().get(0).getSong()
                                        + "\n\n" + "Artist Name: " + response.body().getData().get(0).getSongArtist() + "\n\n" + "App Name: " + context.getResources().getString(R.string.app_name);

                            } else {
                                binding.loader.setVisibility(View.GONE);
                                View dialog_view = LayoutInflater.from(context).inflate(AppUtil.setLanguage(context, R.layout.simple_dialog_text_button), null);
                                final AlertDialog dialog = new AlertDialog.Builder(context)
                                        .setCancelable(false)
                                        .setView(dialog_view)
                                        .show();

                                if (dialog.getWindow() != null)
                                    dialog.getWindow().getDecorView().getBackground().setAlpha(0);

                                ((TextView) dialog_view.findViewById(R.id.dialog_text)).setText(response.body().getMessage());
                                (dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
                                ((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
                                dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
                                    dialog.dismiss();
                                });
                            }
                        } else if (response.body().getStatus() != null && response.body().getStatus().equals(401)) {
                            binding.loader.setVisibility(View.GONE);
                            Intent i = new Intent(context, Login.class);
                            startActivity(i);
                            getActivity().finish();
                        }else {
                            binding.loader.setVisibility(View.GONE);
                            View dialog_view = LayoutInflater.from(context).inflate(AppUtil.setLanguage(context, R.layout.simple_dialog_text_button), null);
                            final AlertDialog dialog = new AlertDialog.Builder(context)
                                    .setCancelable(false)
                                    .setView(dialog_view)
                                    .show();

                            if (dialog.getWindow() != null)
                                dialog.getWindow().getDecorView().getBackground().setAlpha(0);

                            ((TextView) dialog_view.findViewById(R.id.dialog_text)).setText(response.body().getMessage());
                            (dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
                            ((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
                            dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
                                dialog.dismiss();
                            });
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<MusicResponse> call, @NonNull Throwable t) {
                    binding.loader.setVisibility(View.GONE);
                    View dialog_view = LayoutInflater.from(context).inflate(AppUtil.setLanguage(context, R.layout.simple_dialog_text_button), null);
                    final AlertDialog dialog = new AlertDialog.Builder(context)
                            .setCancelable(false)
                            .setView(dialog_view)
                            .show();

                    if (dialog.getWindow() != null)
                        dialog.getWindow().getDecorView().getBackground().setAlpha(0);

                    ((TextView) dialog_view.findViewById(R.id.dialog_text)).setText("Something went wrong! Please try again.");
                    (dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
                    ((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
                    dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
                        dialog.dismiss();
                    });
                }
            });
        } else {
            binding.loader.setVisibility(View.GONE);
            View dialog_view = LayoutInflater.from(context).inflate(AppUtil.setLanguage(context, R.layout.simple_dialog_text_button), null);
            final AlertDialog dialog = new AlertDialog.Builder(context)
                    .setCancelable(false)
                    .setView(dialog_view)
                    .show();

            if (dialog.getWindow() != null)
                dialog.getWindow().getDecorView().getBackground().setAlpha(0);

            ((TextView) dialog_view.findViewById(R.id.dialog_text)).setText(getResources().getString(R.string.no_internet_connection));
            (dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
            ((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
            dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
                dialog.dismiss();
            });
        }
    }
Sleepless answered 27/9, 2023 at 21:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.