0

I'm trying to use Android Retrofit for the first time, I'm following tutorial and get stuck in on of the first steps... 1. Using Gson2.3, okhttp2.1.0, okhttp-urlconnection2.1.0, retrofit-1.8.0 2. my web service is in .php script and returns this kind of data {"idInfo":"12","typeInfo":"2"} 3. I created model class gitmodel

public class gitmodel {
    public gitmodel(int idInfo, int typeInfo) {
        this.idInfo = idInfo;
        this.typeInfo = typeInfo;
    }

    private int idInfo;
    private int typeInfo;
    public gitmodel() {
    }
    public int getIdInfo() {
        return idInfo;
    }
    public void setIdInfo(int idInfo) {
        this.idInfo = idInfo;
    }
    public int getTypeInfo() {
        return typeInfo;
    }
    public void setTypeInfo(int typeInfo) {
        this.typeInfo = typeInfo;
    }
}

" 4. I created interface class gitapi that looks like this

public interface gitapi {

    @GET("/users/{user}")      
    public void getFeed(@Path("user") String user,Callback<gitmodel> response);      
}

I get an error in this class "cannot resolve Path" and cannot resolve gitmodel. I know this is just a start but I cannot go on.

Jure
  • 49
  • 3
  • 7

4 Answers4

0

Using 1.9 version of retrofit, I'm just copy pasting my basic Api class:

compile 'com.squareup.retrofit:retrofit:1.9.0'

public class Api {

    public interface Service {

        @GET("/api/url/something")
        ResponseModelThatYouCreated getSomethingFromGithub(@Body RequestModel requestModelThatYouCreated);

        //other methods can be here
    }

    private static final String API_URL = "http://api.github.com"; //or something else

    private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .build();

    private static final Service ServiceInstance = REST_ADAPTER.create(Service.class);

    public static Service getService() {
        return ServiceInstance;
    }

}

Usage:

ResponseModelThatYouCreated fromGit = Api.getInstance().getSomethingFromGithub(/*parameter object*/)
Ozgur
  • 3,738
  • 17
  • 34
  • Can you please list all the classes, files you are using? – Jure Oct 15 '15 at 16:22
  • There is nothing to list. You will only need your request and response objects like gitModel. – Ozgur Oct 15 '15 at 16:29
  • I have 2 files, POJO with getters and setters (gitmodel) and file in API package that is throwing me error. Can you paste all the files you have in your working example and I'll try to reuse it? – Jure Oct 15 '15 at 17:16
  • I tried using your code, usage part in MainActivity but something is missing – Jure Oct 15 '15 at 19:06
  • What error are you getting? Are you calling your method from Ui thread or from AsyncTask ? – Ozgur Oct 15 '15 at 19:07
  • This is what I did. I used my gitmodel and used your API class. In API class there is an error "ResponseModelThatYouCreated getSomethingFromGithub(@Body RequestModel requestModelThatYouCreated);" and "RestAdapter REST_ADAPTER = new RestAdapter.Builder()" – Jure Oct 15 '15 at 19:30
  • Are you sure you are using 1.9 version of retrofit? – Ozgur Oct 15 '15 at 19:31
  • I have included both 1.9 and 1.8 to project – Jure Oct 15 '15 at 19:41
  • I did, ResAdapter is ok now, but this line is still a problem ResponseModelThatYouCreated getSomethingFromGithub(@Body RequestModel requestModelThatYouCreated); – Jure Oct 15 '15 at 19:45
  • Its because there is no class like "ResponseModelTha.." in your project. Just replace with your models. – Ozgur Oct 15 '15 at 19:46
  • I do not understand what do you mean by Resonse and Request model? From docs I understood I need to have one model class that defines types of data my JSON contains so i did that, the class is the question. I do not get how that fits with this line of code – Jure Oct 15 '15 at 19:56
  • Please check new thread from new example http://stackoverflow.com/questions/33165610/android-retrofit-simple-usage-error?noredirect=1#comment54140201_33165610 – Jure Oct 16 '15 at 11:21
0

you can update your app gradle file with latest retrofit version as:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

you can read how to integrate it in your app with this link

0

How I use Retrofit using Java Generic Types:

You can use the interfaces in "BaseRetrofitHelper" to do Async Calls.

public abstract class BaseRetrofitHelper {

    /** START Callback Interfaces **/    
    public interface IJsonObjectCallback {
        void OnJsonObjectResponse(Integer requestCase, JsonObject answer);
        void OnJsonObjectFailure(Integer requestCase, Throwable t);
    }

    public interface IResponseBodyCallback {
        void OnResponseBodySuccess(Integer reqCase, ResponseBody response);
        void OnResponseBodyError(Integer reqCase, Throwable t);
    }

    public interface IBaseResponseCallback{
        void OnBaseResponseSuccess(Integer requestCase, BaseResponse answer);
        void OnBaseResponseFailure(Integer requestCase, Throwable t);
    }

    public interface IBaseItemResponseCallback<T>{
        void OnBaseItemResponseSuccess(Integer reqCase, BaseItemResponse<T> answer);
        void OnBaseItemResponseError(Integer reqCase, Throwable t);
    }

    public interface IGetItemBaseResponseCallback<T>{
        void OnGetItemBaseResponseSuccess(Integer reqCase, T answer);
        void OnGetItemBaseResponseError(Integer reqCase, Throwable t);
    }

    public interface IBaseItemsResponseCallback<T>{
        void OnBaseItemsResponseSuccess(Integer reqCase, BaseItemsResponse<T> answer);
        void OnBaseItemsResponseError(Integer reqCase, Throwable t);
    }

    public interface IGetItemsBaseResponseCallback<T>{
        void OnGetItemsBaseResponseSuccess(Integer reqCase, List<T> answer);
        void OnGetItemsBaseResponseError(Integer reqCase, Throwable t);
    }
    /** END Callback Interfaces **/

    // Logcats
    protected final String LOGCAT = this.getClass().getSimpleName();
    // Timeouts
    public static final String CONNECT_TIMEOUT = "CONNECT_TIMEOUT";
    public static final String READ_TIMEOUT = "READ_TIMEOUT";
    public static final String WRITE_TIMEOUT = "WRITE_TIMEOUT";

    private static Retrofit mRetrofit;
    private static String mBaseUrl;

    /* INIT YOUR RETROFIT INSTANCE HERE */

    /* START Getter & Setter Methods */
    public static String getBaseUrl() {
        return mBaseUrl;
    }
    /* END Getter & Setter Methods */

    /* START Public Methods */
    public <T> T createService(Class<T> service) {
        return mRetrofit.create(service);
    }
    /* END Public Methods */

    /* START Protected Methods */
    String getJsonRequest(LinkedHashMap<String, String> paramsToJson) {
        Gson gson = new Gson();
        return gson.toJson(paramsToJson, LinkedHashMap.class);
    }

    /* START Sync Request Methods */
    protected <T> T executeSyncCall(ExecutorService exe, Call<T> call){
        return new ResponseExecutorCallable<>(exe, call).executeSyncCall();
    }

    public <T> T executeSyncCall(Call<T> call){
        return new ResponseExecutorCallable<>(newSingleThreadExecutor(), call).executeSyncCall();
    }

    public boolean getBaseResponseSuccess(Call<? extends  BaseResponse> call){
        return new BaseResponseExecutorCallable<>(newSingleThreadExecutor(), call).getBaseResponseSuccess();
    }

    String getBaseResponseMessage(Call<? extends BaseResponse> call){
        return new BaseResponseExecutorCallable<>(newSingleThreadExecutor(), call).getBaseResponseMessage();
    }

    protected <T> List<T> getBaseResponseItems(Call<BaseItemsResponse<T>> call){
        return new BaseItemsResponseExecutorCallable<T>(newSingleThreadExecutor(), call).getBaseResponseItems();
    }

    protected <T> T getBaseResponseItem(Call<BaseItemResponse<T>> call){
        return new BaseItemResponseExecutorCallable<T>(newSingleThreadExecutor(), call).getBaseResponseItem();
    }
    /* END Sync Request Methods */

    /* START Check Methods */
    protected JsonObject checkGetJsonObject(Response<JsonObject> response){
        JsonObject answer = null;
        if(response != null && response.isSuccessful()){
            answer = response.body();
        }
        return answer;
    }

    ResponseBody checkResponseBody(Response<ResponseBody> response){
        ResponseBody answer = null;
        if(response != null && response.isSuccessful()){
            answer = response.body();
        }
        return answer;
    }

    protected BaseResponse checkBaseResponse(Response<BaseResponse> response){
        BaseResponse answer = null;
        if(response != null && response.isSuccessful()){
            answer = response.body();
        }
        return answer;
    }

    protected <T> BaseItemResponse<T> checkBaseItemResponse(Response<BaseItemResponse<T>> response){
        BaseItemResponse<T> answer = null;
        if(response != null && response.isSuccessful()){
            answer = response.body();
        }
        return answer;
    }

    protected <T> T checkGetBaseResponseItem(Response<BaseItemResponse<T>> response){
        T item = null;
        if(response != null && response.isSuccessful()){
            BaseItemResponse<T> answer = response.body();
            if(answer != null && answer.getSuccess()){
                item = answer.getItem();
            }
        }
        return item;
    }

    <T> BaseItemsResponse<T> checkBaseItemsResponse(Response<BaseItemsResponse<T>> response){
        BaseItemsResponse<T> answer = null;
        if(response != null && response.isSuccessful()){
            answer = response.body();
        }
        return answer;
    }

    protected <T> List<T> checkGetBaseResponseItems(Response<BaseItemsResponse<T>> response){
        List<T> items = null;
        if(response != null && response.isSuccessful()){
            BaseItemsResponse<T> answer = response.body();
            if(answer != null && answer.getSuccess()){
                items = answer.getItems();
            }
        }
        return items;
    }
    /* END Check Methods *//* END Protected Methods */

    /** START Private Classes **/
    private class ResponseExecutorCallable<T> implements Callable<T>{
        private ExecutorService mExecutorService;
        private Call<T> mCall;

        ResponseExecutorCallable(ExecutorService exe, Call<T> call){
            this.mExecutorService = exe;
            this.mCall = call;
        }

        /* START Override Callable Methods */
        @Override
        public T call() {
            T ret = null;
            try {
                Response<T> response = mCall.execute();
                if (response != null && response.isSuccessful()) {
                    ret = response.body();
                }
            } catch(IOException ioE){
                onException(ioE);
            }
            return ret;
        }
        /* END Override Callable Methods */

        /* START Public Methods */
        T executeSyncCall(){
            T ret = null;
            try{
                ret = mExecutorService.submit(this).get();
            } catch(ExecutionException | InterruptedException eiE){
                onException(eiE);
            }
            return ret;
        }
        /* END Public Methods */
    }

    private class BaseResponseExecutorCallable<T extends BaseResponse> extends ResponseExecutorCallable<T> {

        BaseResponseExecutorCallable(ExecutorService exe, Call<T> call){
            super(exe, call);
        }

        /* START Public Methods */
        boolean getBaseResponseSuccess(){
            boolean ret = false;
            T res = super.executeSyncCall();
            if(res != null){
                ret = res.getSuccess();
            }
            return ret;
        }

        String getBaseResponseMessage(){
            String ret = null;
            T res = super.executeSyncCall();
            if(res != null && res.getSuccess()){
                ret = res.getMsg();
            }
            return ret;
        }
        /* END Public Methods */
    }

    private class BaseItemResponseExecutorCallable<T> extends BaseResponseExecutorCallable<BaseItemResponse<T>>{

        BaseItemResponseExecutorCallable(ExecutorService exe, Call<BaseItemResponse<T>> call){
            super(exe, call);
        }

        /* START Public Methods */
        <T> T getBaseResponseItem(){
            T ret = null;
            BaseItemResponse<T> res = (BaseItemResponse<T>) super.executeSyncCall();
            if(res != null && res.getSuccess()){
                ret = res.getItem();
            }
            return ret;
        }
        /* END Public Methods */
    }

    private class BaseItemsResponseExecutorCallable<T> extends BaseResponseExecutorCallable<BaseItemsResponse<T>>{

        BaseItemsResponseExecutorCallable(ExecutorService exe, Call<BaseItemsResponse<T>> call){
            super(exe, call);
        }

        /* START Public Methods */
        <T> List<T> getBaseResponseItems(){
            List ret = null;
            BaseItemsResponse<T> res = (BaseItemsResponse<T>) super.executeSyncCall();
            if(res != null && res.getSuccess()){
                ret = res.getItems();
            }
            return ret;
        }
        /* END Public Methods */
    }
    /** END Private Classes **/

}

My Responses:

public class BaseResponse {

    @SerializedName("success")
    protected Boolean mSuccess;
    @SerializedName("msg")
    protected String mMsg;
    @SerializedName("errors")
    protected String mErrors;

    /* START Getter & Setter Methods */
    public Boolean getSuccess() {
        return mSuccess;
    }

    public void setSuccess(Boolean success) {
        this.mSuccess = success;
    }

    public String getMsg() {
        return mMsg;
    }

    public void setMsg(String msg) {
        this.mMsg = msg;
    }

    public String getErrors() {
        return mErrors;
    }

    public void setErrors(String errors) {
        this.mErrors = errors;
    }
    /* END Getter & Setter Methods */

    @Override
    public String toString() {
        return "BaseResponse{" +
            "mSuccess=" + mSuccess +
            ", mMsg='" + mMsg + '\'' +
            ", mErrors='" + mErrors + '\'' +
            '}';
    }

}

public class BaseItemResponse<T> extends BaseResponse {

    @SerializedName(value = "item", alternate = {"..."})
    private T mItem;

    /* START Getter & Setter Methods */
    public T getItem() {
        return mItem;
    }

    public void setItem(T mItem) {
        this.mItem = mItem;
    }
    /* END Getter & Setter Methods */

    @Override
    public String toString() {
        return "BaseItemResponse{" +
            "mItem=" + mItem +
            ", mSuccess=" + mSuccess +
            ", mMsg='" + mMsg + '\'' +
            ", mErrors='" + mErrors + '\'' +
            '}';
    }

}



public class BaseItemsResponse<T> extends BaseResponse {

    @SerializedName(value = "items", alternate = {"...."})
    private List<T> mItems;

    /* START Getter & Setter Methods */
    public List<T> getItems() {
        return mItems;
    }

    public void setItems(List<T> items) {
        this.mItems = items;
    }
    /* END Getter & Setter Methods */

    @Override
    public String toString() {
        return "BaseItemsResponse{" +
            "mItems=" + mItems +
            ", mSuccess=" + mSuccess +
            ", mMsg='" + mMsg + '\'' +
            ", mErrors='" + mErrors + '\'' +
            '}';
    }

}

Usage for Sync Calls:

Create a "RetrofitHelper" class which extends "BaseRetrofitHelper". In this class make your methods. You can do a Sync call in another thread which will wait until it finished the Networking Operation just doing this:

public List<YOURCLASS> requestSyncListYOURCLASS(String url, String token, HashMap<String, Object> data){
        YourAPI api = createService(YourAPI.class);
        String params = JsonUtils.buildB64EncodedParams(token, data);
        Call<BaseItemsResponse<YOURCLASS>> call = api.getListYOURCLASS(url, params);
        return super.getBaseResponseItems(call);
    }

With this method you get a List of "YOURCLASS" elements in your activity. The networking operation is done in an another thread so you won't get the 'NetworkingOnMainThreadException' and also you don't need to set the 'Policy' to 'PermitAll' to solve the 'NetworkingOnMainThreadException'. (Change the policy to permit networking in your main thread is really a bad thing!)

Usage for Async Calls:

Personally I prefer to always use, when possible, Async Calls to do networking operation. That's why in the Interfaces you have a 'Integer requestCase' parameter: when you have to do multiple networking operations whose use all the same Callback you just need to pass an integer value as 'requestCase' (reqCase) which will identify which operation finished. In the 'Success' and 'Error' callback methods you just need to put a 'switch(requestCase)' statement to know which operation finished and returned his results.

----> When you implement the callback interface in your activity you can specify the result's class you expect as his Type Parameter, if you will always get back the same class of objects when the networking operations return. Otherwise if you have multiple kind of object classes returned using the same callback methods you should not give a Type Parameter to the Interface when you implements it.

public void requestAsyncListYOURCLASS(String url, String token, HashMap<String, Object> data, final Integer reqCase,
                                       final IGetItemsBaseResponseCallback<YOURCLASS> callback) {
String params = JsonUtils.buildB64EncodedParams(token, data);
        YourAPI api = createService(YourAPI.class);
        Call<BaseItemsResponse<YOURCLASS>> call = api.getListYOURCLASS(url, params);
        call.enqueue(new Callback<BaseItemsResponse<YOURCLASS>>() {
            @Override
            public void onResponse(Call<BaseItemsResponse<YOURCLASS>> call, Response<BaseItemsResponse<YOURCLASS>> response) {
                callback.OnGetItemsBaseResponseSuccess(reqCase, checkGetBaseResponseItems(response));
            }

            @Override
            public void onFailure(Call<BaseItemsResponse<YOURCLASS>> call, Throwable t) {
                callback.OnGetItemsBaseResponseError(reqCase, t);
            }
        });
    }

Hope this is helpful for you! Thank you, Bye All :D

Community
  • 1
  • 1
Z3R0
  • 1,011
  • 10
  • 19
  • Regarding the last lines of your answer: please take the time to read [answer]. – jpeg Feb 01 '19 at 14:11
  • And? They put reputation to make comment and give points to other people... This is really bad for me. I asked because I just need the reputation to give points to other people and to comment their answer. That's all. – Z3R0 Feb 01 '19 at 19:50
  • Oh sorry, you though I didn't know how to answer to people's question. My bad, I mean that I need reputation to send comments to others people answers and to give them reputation, because now I can't for my low reputatation. ) : Thank you for your comment, hope me code is helpful for you (: have a nice day and c0d1n6! – Z3R0 Feb 01 '19 at 19:58
  • No worries. I just meant, writing thanks and bye does not add any informative value to your answer, this is probably why this is not welcome on stackoverflow. And the sentence about voting and reputation also does not add value to the answer, although it might be right, this sentence would be more suitable in a comment IMHO. – jpeg Feb 01 '19 at 21:06
  • Ok I will keep that in mind. But did you find that code useful? – Z3R0 Feb 02 '19 at 05:08
  • I'm mot able to judge whether your code is useful, I don't know this topic. I was only reviewing the form of your post, not the content. But I hope the community will upvote your post if they find it useful. Good luck on stackoverflow! By the way a rather easy way to begin with reputation is to edit posts in your tags of expertise, there are often posts needing improvement. – jpeg Feb 02 '19 at 09:56
0

Try these following steps:

  1. Add gradle and sync your project

implementation 'com.squareup.retrofit2:retrofit:2.0.2'

implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

  1. create your pojo class and add in model class like this

     public class LoginModel {
     @SerializedName("code")
     @Expose
     private String code;
     @SerializedName("message")
     @Expose
     private String message;
     @SerializedName("data")
     @Expose
      private Data data;
    
       public String getCode() {
       return code;
       }
    
      public void setCode(String code) {
      this.code = code;
     }
    
     public String getMessage() {
     return message;
     }
    
     public void setMessage(String message) {
     this.message = message;
     }
    
     public Data getData() {
      return data;
     }
    
    public void setData(Data data) {
    this.data = data;
    }
    
    public class Data {
    
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("facebookId")
    @Expose
    private String facebookId;
    @SerializedName("password")
    @Expose
    private String password;
    @SerializedName("securityHash")
    @Expose
    private String securityHash;
    @SerializedName("userName")
    @Expose
    private String userName;
    @SerializedName("firstName")
    @Expose
    private String firstName;
    @SerializedName("lastName")
    @Expose
    private String lastName;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("contact")
    @Expose
    private String contact;
    @SerializedName("userLastLoggedIn")
    @Expose
    private String userLastLoggedIn;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("createdAt")
    @Expose
    private String createdAt;
    @SerializedName("updatedAt")
    @Expose
    private String updatedAt;
    @SerializedName("profileStatus")
    @Expose
    private String profileStatus;
    @SerializedName("gender")
    @Expose
    private String gender;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getFacebookId() {
        return facebookId;
    }
    
    public void setFacebookId(String facebookId) {
        this.facebookId = facebookId;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getSecurityHash() {
        return securityHash;
    }
    
    public void setSecurityHash(String securityHash) {
        this.securityHash = securityHash;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    public String getContact() {
        return contact;
    }
    
    public void setContact(String contact) {
        this.contact = contact;
    }
    
    public String getUserLastLoggedIn() {
        return userLastLoggedIn;
    }
    
    public void setUserLastLoggedIn(String userLastLoggedIn) {
        this.userLastLoggedIn = userLastLoggedIn;
    }
    
    public String getStatus() {
        return status;
    }
    
    public void setStatus(String status) {
        this.status = status;
    }
    
    public String getCreatedAt() {
        return createdAt;
    }
    
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
    
    public String getUpdatedAt() {
        return updatedAt;
    }
    
    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }
    
    public String getProfileStatus() {
        return profileStatus;
    }
    
    public void setProfileStatus(String profileStatus) {
        this.profileStatus = profileStatus;
    }
    
    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
    
    }
    }
    
  2. add three class in your package

  • RetrofitApiInterfaces
  • RetrofitClient
  • RetrofitConstent

1.1 Add RetrofitApiInterface Calss like this:


 public interface RetrofitApiInterface {

/*Login API Post Method*/
@POST("login")
@FormUrlEncoded
Call<LoginModel> loginMethod(@Field("email") String email, @Field("password") String password);
 }

1.2 Add RetrofitClient calss


public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}

1.3 Add RetrofitConstent class


public class RetrofitConstent {
public static String BASE_URL="";

public static RetrofitApiInterface retrofitApiInterface(){
    return RetrofitClient.getClient(BASE_URL).create(RetrofitApiInterface.class);
}
 }

4. Add Retrofit api method like this


   /*simple login API method*/
public void loginAPIMethod(String email, String password) {
    dialog = new Dialog(this, android.R.style.Theme_Translucent);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom_progress_dialog);
    dialog.setCancelable(false);
    dialog.show();
    Call<LoginModel> call = null;
    try {
        call = YabbyConstant.retrofitApiInterface().loginMethod(email, password);
        call.enqueue(new Callback<LoginModel>() {
            @Override
            public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
                /*getting success response */
                Log.e(TAG + "Response", "" + response.body().getCode());
                try {
                    if (response.body().getCode().equalsIgnoreCase("1")) {
                        dialog.dismiss();
                        LoginModel.Data data = response.body().getData();
                        /*save data into shared preference*/
                        Preference.storeUserPreferences(SignInActivity.this, ApiUtils.USER, new Gson().toJson(response.body().getData()));
                        Log.e(TAG, "sharedLogin" + new Gson().toJson(response.body().getData()));
                        Log.e(TAG, "id" + String.valueOf(data.getId()));
                        Log.e(TAG, "email" + String.valueOf(data.getEmail()));
                        finish();
                        startActivity(new Intent(SignInActivity.this, HomeScreenActivity.class));
                        overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
                        String message = response.body().getMessage();
                        Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_SHORT).show();
                    } else {
                        String data = response.body().getMessage();
                        alertDialogueFail(data);
                        Log.e(TAG, "data--" + data);
                        dialog.dismiss();
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            /* getting failure response*/
            @Override
            public void onFailure(Call<LoginModel> call, Throwable t) {
                dialog.dismiss();
                Log.e("Error", "" + String.valueOf(t.getMessage()));
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Please Check my code how retrofit used

i hope its helps you

Android Geek
  • 8,956
  • 2
  • 21
  • 35