Saturday, 7 May 2016

Android apis Calling through Retrofit

Hi guys,

Today i'll show you how to use RetroFit for calling any apis.

Follow some belew step and get it done in easy way.

Step 1.

Compile these  libraries from gradle

    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Step 2.

Create Interface for calling apis like below

public interface Api {

    // Added server url here, and pass reference of model class, model class you can generate by GSON or manually.

    @POST("/*******/loginapi")
    Call<LoginModal> loginapi(@Body JsonObject data);
}

Step 3.

  Third step to write code on replacement of AsyncTask, calling api

   private void LoginService(JsonObject jsonPostParameters) {
        //While the app fetched data we are displaying a progress dialog

        final ProgressDialog loading = ProgressDialog.show(activity, "", "Please wait...", false, false);

        OkHttpClient okHttpClient1 = new com.squareup.okhttp.OkHttpClient();
        okHttpClient1.setReadTimeout(Common.api_timeinterval, TimeUnit.SECONDS);
        okHttpClient1.setConnectTimeout(Common.api_timeinterval, TimeUnit.SECONDS);

// Pass server base url, i:e www.yoursiteurl.com
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient1)
                .build();

        Api serviceApi = retrofit.create(Api.class);
        // Call<Register> updateUser(@Query("name") String name, @Query("password") String password,@Query("email")String email,@Query("Country") String Country  ,@Query("latitude") String latitude ,@Query("longitude") String longiTude  , @Query("device_token") String device_token );

        serviceApi.loginapi(jsonPostParameters).enqueue(new Callback<LoginModal>() {
            @Override
            public void onResponse(Response<LoginModal> response, Retrofit retrofit) {
                LoginModal loginmodal = response.body();
                loading.dismiss();

                if (loginmodal.getResponse().getResult() == 1) {

// Here you get reponse from model class
 
                } else {
                    Common.showDialogActionLess("Login unsuccessfull !", loginmodal.getResponse().getErrorMSG(),
                            activity);
                }

            }

            @Override
            public void onFailure(Throwable e) {
                loading.dismiss();
                if (e instanceof HttpRetryException) {
                    HttpRetryException response = (HttpRetryException) e;
                }

                Toast.makeText(activity, "Please try again later.", Toast.LENGTH_LONG).show();
                finish();

            }
        });

    }


Step 4.

If you want then take reference from model class :

public class LoginModal {
 
    private ResponseEntity Response;

    public void setResponse(ResponseEntity Response) {
        this.Response = Response;
    }

    public ResponseEntity getResponse() {
        return Response;
    }

    public static class ResponseEntity {
        private int result;
        private String resultText;
        private String errorMSG;
        private int user_id;
 
        public void setResult(int result) {
            this.result = result;
        }

        public void setResultText(String resultText) {
            this.resultText = resultText;
        }

        public void setErrorMSG(String errorMSG) {
            this.errorMSG = errorMSG;
        }

        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }

        public int getResult() {
            return result;
        }

        public String getResultText() {
            return resultText;
        }

        public String getErrorMSG() {
            return errorMSG;
        }
    }
}


Step 5.

Atlast create json or anyformat you want to send to server and call api method.


                    JsonObject jsonObject = new JsonObject();
                    try {
                        jsonObject.addProperty("username", "abc");
                        jsonObject.addProperty("password", "xyz");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    LoginService(jsonObject);



That's all this is the easy and frequent way to call apis from RetroFit.Hopefully somebody will help from this. :)

1 comment: