Pages

Sunday, August 20, 2017

Working with Retrofit 2.0 library and learn how to use it.

Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice.

First of All Add Gradle dependency to your app build.gradle file
//Retrofit
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

//Butter Knief
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

//Optional if required
useLibrary 'org.apache.http.legacy'

Step 1) Create ServiceGenerator.java class

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://XXX.XXXX.com/";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    // Request customization: add request headers
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", authToken)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }

        OkHttpClient client = httpClient.readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);

    }
}

Step 2) Create Model Class

public class Category{
     public String id;
     public String category;
}


Step 3) Create Interface with api declaration inside it.

public interface Webservicecall {
   
    @GET("api/v1.0/categories")
    Call<Category> getCategory();

}





Step 4) Now call the api using retrofit


//Webservicecall webservicecall = ServiceGenerator.createService(Webservicecall.class,token);

Webservicecall webservicecall = ServiceGenerator.createService(Webservicecall.class);

Call<Category> getCategory_call = webservicecall.getCategory();

showProgressDialog();

getCategory_call.enqueue(new Callback<Category>() {

            @Override
            public void onResponse(Call<Category> call, Response<Category> response) {

            hideProgressDialog();

            }


            @Override
            public void onFailure(Call<Category> call, Throwable t) {
                hideProgressDialog();
            }

        }); 

Step 5) Show Progress dialog

ProgressDialogFragment progressDialogFragment = null;

public void showProgressDialog() {
        progressDialogFragment = new ProgressDialogFragment("");
        progressDialogFragment.show(getFragmentManager(), "");
        progressDialogFragment.setCancelable(false);
    }

public void hideProgressDialog() {
      try {
           if (progressDialogFragment != null) {
               progressDialogFragment.dismiss();
           }
        } catch (Exception e) {
        }
    }

Step 6) ProgressDialogFragment.java


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

@SuppressLint("ValidFragment")
public class ProgressDialogFragment extends DialogFragment {
 private String message;

 public ProgressDialogFragment() {
  this.message = "";
 }

 public ProgressDialogFragment(String message) {
  this.message = message;
 }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  Dialog loading = new Dialog(getActivity());
  loading.setContentView(R.layout.layout_progress);
  loading.setCancelable(false);

  loading.getWindow().setBackgroundDrawable(
    new ColorDrawable(Color.TRANSPARENT));
  loading.getWindow().setLayout(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
  int divierId = loading.getContext().getResources()
    .getIdentifier("android:id/titleDivider", null, null);
  View divider = loading.findViewById(divierId);
  if(divider!=null) {
   divider.setBackgroundColor(Color.TRANSPARENT);
  }

  loading.show();
  return loading;
 }
}



==>layout_progress.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:id="@+id/RelativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@color/whitebackground"
    android:gravity="center_vertical"
    android:orientation="horizontal">

</RelativeLayout>

No comments:

Post a Comment