<h3><span style="color: #000080;"><strong>Retrofit</strong></span></h3>
<p>Retrofit is a<strong><span style="color: #008000;"> REST Client</span></strong> for Android and Java developed by <strong><span style="color: #008000;">Square</span></strong>. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a <strong><span style="color: #008000;">REST based webservice</span></strong>. In Retrofit you configure which converter is used for the data serialization. Typically for JSON you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the <strong><span style="color: #008000;">OkHttp library for HTTP requests</span></strong>.</p>
<p>Get <span style="color: #0000ff;"><strong>GITHUB</strong></span> code from <span style="color: #0000ff;"><a style="color: #0000ff;" href="https://github.com/arunk7839/RetrofitExample"><strong>here</strong></a>.</span></p>
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="XuueDLBJYqk" title="Android Retrofit Example"><a placeholder href="https://youtu.be/XuueDLBJYqk"><img src="https://i.ytimg.com/vi/XuueDLBJYqk/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Retrofit Example"></a></amp-youtube></p>
<h3><span style="color: #000080;"><strong>Using Retrofit</strong></span></h3>
<p>To work with <strong><span style="color: #008000;">Retrofit</span></strong> you need basically three classes.</p>
<ul>
<li><span style="color: #008000;"><strong>Model class</strong></span> which is used to map the JSON data.</li>
<li><strong><span style="color: #008000;">Builder class &#8211; Instance</span></strong> which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.</li>
<li><span style="color: #008000;"><strong>Interfaces</strong></span> which defines the possible HTTP operations.</li>
</ul>
<h3></h3>
<h3><span style="color: #000080;"><strong>Getting Cric API Key / Sample JSON</strong></span></h3>
<p><strong> </strong>In this tutorial we will use The <span style="color: #008000;"><strong>Cric API</strong></span>. In order to use this API it is necessary to obtain the <span style="color: #008000;"><strong>API key</strong></span>. <span style="color: #000080;"><strong><a style="color: #000080;" href="http://www.cricapi.com/" target="_blank" rel="noopener noreferrer">Here</a></strong></span> you need to register and login in order to obtain the key.</p>
<p>This is the <strong><span style="color: #008000;">Json</span></strong> format provided by the <strong><span style="color: #008000;">Cric API</span></strong> under <span style="color: #008000;"><strong>MatchCalender</strong></span>.</p>
<p><img class="alignnone wp-image-270 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/Capture-2.jpg" alt="" width="355" height="205" /></p>
<p><span style="color: #000080;"><strong>Extended form of above Json.</strong></span></p>
<p><img class="alignnone wp-image-271 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/json3.jpg" alt="" width="489" height="466" /></p>
<h3><strong><span style="color: #000080;"> Creating New Project</span></strong></h3>
<ol>
<li>Create a new project in Android Studio from <span style="color: #008000;"><strong>File </strong><strong>⇒</strong><strong> New Project</strong>.</span> When it prompts you to select the default activity, select<span style="color: #008000;"> </span><strong><span style="color: #008000;">Empty Activity</span> </strong>and proceed.</li>
<li>Open <span style="color: #008000;"><strong>build.</strong><strong>gradle </strong></span>and add <span style="color: #008000;"><strong>Retrofit</strong>, <strong>Gson </strong></span>dependencies.</li>
</ol>
<p><span style="color: #008000;"><span style="color: #0000ff;"><strong>build.</strong></span><strong><span style="color: #0000ff;">gradle</span> </strong></span></p>
<pre>dependencies {
 implementation fileTree(dir: 'libs', include: ['*.jar'])
 implementation 'com.android.support:appcompat-v7:26.1.0'

 <strong><span style="color: #008000;">//retrofit,json</span></strong>
 compile 'com.google.code.gson:gson:2.6.2'
 compile 'com.squareup.retrofit2:retrofit:2.0.2'
 compile 'com.squareup.retrofit2:converter-gson:2.0.2'
 
}
</pre>
<p>3.Since we are working with network operations we need to add<span style="color: #008000;"> <strong>INTERNET </strong></span>permissions in <span style="color: #008000;"><strong>AndroidManifest.</strong><strong>xml </strong></span>file.</p>
<p><span style="color: #0000ff;"><strong>AndroidManifest.</strong><strong>xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.lenovo.cricketmatchapp">;

 <strong><span style="color: #008000;"><;uses-permission android:name="android.permission.INTERNET"/>;</span></strong>
 
 <;application
 android:allowBackup="true"
 android:icon="@drawable/ic_ball"
 android:label="@string/app_name"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">;

 <;activity android:name=".activity.MainActivity">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

 <;category android:name="android.intent.category.LAUNCHER" />;
 <;/intent-filter>;
 <;/activity>;

 <;/application>;

<;/manifest>;

</pre>
<p>4.Create four sub-packages named <span style="color: #008000;"><strong>activity</strong>, <strong>adapter</strong>, <strong>rest </strong><span style="color: #000000;">and</span> <strong>model </strong></span>in your main package.</p>
<h3><strong><span style="color: #000080;">Creating Model Class</span></strong></h3>
<p>Using this <span style="color: #008000;">route</span> <strong>(<span style="color: #008000;"><a style="color: #008000;" href="http://www.cricapi.com/api/matchCalendar/?apikey=INSERT_YOUR_API_KEY">http://www.cricapi.com/api/matchCalendar/?apikey=INSERT_YOUR_API_KEY</a></span>)</strong> we get the total matches of this year.</p>
<p>In this <strong><span style="color: #008000;"> Json</span></strong> format <strong><span style="color: #008000;"> data[ ]</span></strong> is the array of object consists of <strong><span style="color: #008000;">unique_id</span></strong>,<strong><span style="color: #008000;">name</span></strong>,<span style="color: #008000;"><strong>date</strong></span>.</p>
<p><img class="alignnone wp-image-267 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/json2.jpg" alt="" width="414" height="374" /></p>
<p>5.Create a class named <span style="color: #008000;"><strong>CalenderResponse.java </strong></span>and <span style="color: #008000;"><strong>MatchCalender.java</strong></span> under <span style="color: #008000;"><strong>model </strong></span>package.</p>
<p><span style="color: #0000ff;"><strong>CalenderResponse.java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.model;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class CalenderResponse {
 @SerializedName("data")
 private List<;MatchCalender>; data;

 public List<;MatchCalender>; getData() {
 return data;
 }

 public void setData(List<;MatchCalender>; data) {
 this.data = data;

 }
}

</pre>
<p><span style="color: #0000ff;"><strong>MatchCalender.java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.model;

import com.google.gson.annotations.SerializedName;

public class MatchCalender {

 @SerializedName("unique_id")
 private String uniqueId;

 @SerializedName("name")
 private String name;


 @SerializedName("date")
 private String date;

 public MatchCalender(String uniqueId, String name, String date) {
 this.uniqueId = uniqueId;
 this.name = name;
 this.date = date;

 }

 public String getUniqueId() {
 return uniqueId;
 }

 public void setUniqueId(String uniqueId) {
 this.uniqueId = uniqueId;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getDate() {
 return date;
 }

 public void setDate(String date) {
 this.date = date;
 }
}</pre>
<h3><strong><span style="color: #000080;">Creating the Retrofit instance</span></strong></h3>
<p>6. To send network requests to an API, we need to use the <strong><span style="color: #008000;">Retrofit Builder class</span></strong> and specify the base URL for the service. So, create a class named <span style="color: #008000;"><strong>ApiClient.</strong> </span><strong><span style="color: #008000;">java</span> </strong>under <span style="color: #008000;"><strong>rest</strong> </span>package.</p>
<p>Here<span style="color: #008000;"> <strong>BASE_URL</strong></span> – it is basic URL of our API. We will use this URL for all requests later.</p>
<p><span style="color: #0000ff;"><strong>ApiClient.</strong> <strong>java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.rest;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
 public static final String BASE_URL = "http://cricapi.com/";
 public static Retrofit retrofit = null;

 public static Retrofit getClient() {
 if (retrofit == null) {
 retrofit = new Retrofit.Builder()
 .baseUrl(BASE_URL)
 .addConverterFactory(GsonConverterFactory.create())
 .build();
 }
 return retrofit;
 }

}
</pre>
<h3><span style="color: #000080;"><strong>Defining endpoints inside of an interface</strong></span></h3>
<p>The endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method. Interfaces defines the possible HTTP operations</p>
<p>7.Create <span style="color: #008000;"><strong>ApiInterface.</strong></span><strong><span style="color: #008000;">java</span> </strong>under <span style="color: #008000;"><strong>rest </strong></span>package.</p>
<p>So, using this route the retrofit will generate the following URL:<br />
<span style="color: #008000;"><strong>http://www.cricapi.com/api/matchCalendar/?apikey=INSERT_YOUR_API_KEY</strong></span></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<p><span style="color: #0000ff;"><strong>ApiInterface.</strong><strong>java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.rest;
import com.example.lenovo.cricketmatchapp.model.CalenderResponse;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface {

 @GET("api/matchCalendar")
 Call<;CalenderResponse>; getMatchCalender(@Query("apikey") String apiKey);

}
</pre>
<p>Take a look to other annotations:</p>
<p><span style="color: #008000;"><em><strong>@Path</strong></em></span> – variable substitution for the API endpoint. For example movie id will be swapped for{id} in the URL endpoint.</p>
<p><span style="color: #008000;"><em><strong>@Query</strong></em></span> – specifies the query key name with the value of the annotated parameter.</p>
<p><span style="color: #008000;"><em><strong>@Body</strong></em></span> – payload for the POST call</p>
<p><span style="color: #008000;"><em><strong>@Header</strong></em> </span>– specifies the header with the value of the annotated parameter</p>
<h3><span style="color: #000080;"><strong>Making the Request</strong></span></h3>
<p>8.Let’s make the request from our <strong><span style="color: #008000;">MainActivity</span></strong>. Open the <span style="color: #008000;"><strong>MainActivity.java </strong></span>and do the below changes. Make sure that your replaced <span style="color: #008000;"><strong>API_KEY</strong></span> should be correct.</p>
<p><span style="color: #0000ff;"><strong>MainActivity.java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.example.lenovo.cricketmatchapp.R;
import com.example.lenovo.cricketmatchapp.adapter.MatchCalenderAdapter;
import com.example.lenovo.cricketmatchapp.model.CalenderResponse;
import com.example.lenovo.cricketmatchapp.model.MatchCalender;
import com.example.lenovo.cricketmatchapp.rest.ApiClient;
import com.example.lenovo.cricketmatchapp.rest.ApiInterface;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

 private final static String API_KEY = "kAv1Vdcj8teYg5QnVmAACIofzdg2";
 private static final String TAG = MainActivity.class.getSimpleName();
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

 Call<;CalenderResponse>; call = apiService.getMatchCalender(API_KEY);
 call.enqueue(new Callback<;CalenderResponse>;() {
 @Override
 public void onResponse(Call<;CalenderResponse>; call, Response<;CalenderResponse>; response) {
 int statuscode = response.code();
 List<;MatchCalender>; matchlist = response.body().getData();
 
 }

 @Override
 public void onFailure(Call<;CalenderResponse>; call, Throwable t) {
 Log.e(TAG, t.toString());
 }
 });
 }
}
</pre>
<p><strong><span style="color: #008000;">Retrofit</span></strong> will download and parse the API data on a background thread, and then return the results back to the UI thread via the<strong><span style="color: #008000;"> onResponse</span></strong> or <span style="color: #008000;"><strong>onFailure </strong></span>method.</p>
<h3><strong><span style="color: #000080;">Displaying the Results in RecyclerView</span></strong></h3>
<p>9.Let’s use <strong><span style="color: #008000;">RecyclerView</span></strong> for fetched results. First of all, add it to the <span style="color: #008000;"><strong>build.gradle.</strong></span></p>
<p><span style="color: #0000ff;"><strong>build.gradle</strong></span></p>
<pre>dependencies {
 implementation fileTree(dir: 'libs', include: ['*.jar'])
 implementation 'com.android.support:appcompat-v7:26.1.0'

 <strong><span style="color: #008000;">//recyclerView</span></strong> 
 compile 'com.android.support:recyclerview-v7:26.1.0'
 
}

</pre>
<p>10.Create a layout named <span style="color: #008000;"><strong>match_calender_item.xml </strong></span>under res layout.</p>
<p><span style="color: #0000ff;"><strong>match_calender_item.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:background="@drawable/bg_color"
 >;

 <;TextView
 android:id="@+id/date"
 android:padding="5dp"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentRight="true"
 android:layout_marginBottom="10dp"
 android:layout_marginRight="20dp"
 android:layout_marginTop="8dp"
 android:textColor="@color/colorPrimaryDark"
 android:textSize="20sp"
 android:textStyle="bold" />;

 <;TextView
 android:id="@+id/name"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="5dp"
 android:layout_marginBottom="8dp"
 android:textAllCaps="true"
 android:textColor="@android:color/white"
 android:textSize="20sp"
 android:textStyle="bold" />;



<;/LinearLayout>;

</pre>
<p>11.Adapter is a common pattern which helps to bind view and data, so let’s implement adapter for this.</p>
<p>Create a class named <span style="color: #008000;"><strong>MatchCalenderAdapter.java</strong></span> under <span style="color: #008000;"><strong>adapter</strong></span> package.</p>
<p><span style="color: #0000ff;"><strong>MatchCalenderAdapter.java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lenovo.cricketmatchapp.R;
import com.example.lenovo.cricketmatchapp.model.MatchCalender;

import java.util.List;


public class MatchCalenderAdapter extends RecyclerView.Adapter<;MatchCalenderAdapter.MatchCalenderViewHolder>; {

 List<;MatchCalender>; matchlist;
 Context context;
 
 public static class MatchCalenderViewHolder extends RecyclerView.ViewHolder {

 TextView name;
 TextView date;

 public MatchCalenderViewHolder(View v) {
 super(v);
 name = (TextView) v.findViewById(R.id.name);
 date = (TextView) v.findViewById(R.id.date);
 }

 }

 public MatchCalenderAdapter(List<;MatchCalender>; matchlist, Context context) {
 this.matchlist = matchlist;
 this.context = context;

 }

 @Override
 public void onBindViewHolder(MatchCalenderViewHolder holder, int position) {
 holder.date.setText(matchlist.get(position).getDate());
 holder.name.setText(matchlist.get(position).getName());
 }

 @Override
 public MatchCalenderAdapter.MatchCalenderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.match_calender_item, parent, false);
 return new MatchCalenderViewHolder(view);

 }

 @Override
 public int getItemCount() {
 return matchlist.size();
 }
}
</pre>
<p>12.Open <span style="color: #008000;"><strong>MainActivity. java </strong></span>and modify the code as below.</p>
<p><span style="color: #0000ff;"><strong>MainActivity. java</strong></span></p>
<pre>package com.example.lenovo.cricketmatchapp.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.example.lenovo.cricketmatchapp.R;
import com.example.lenovo.cricketmatchapp.adapter.MatchCalenderAdapter;
import com.example.lenovo.cricketmatchapp.model.CalenderResponse;
import com.example.lenovo.cricketmatchapp.model.MatchCalender;
import com.example.lenovo.cricketmatchapp.rest.ApiClient;
import com.example.lenovo.cricketmatchapp.rest.ApiInterface;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends AppCompatActivity {

 private final static String API_KEY = "kAv1Vdcj8teYg5QnVmAACIofzdg2";
 private static final String TAG = MainActivity.class.getSimpleName();
 RecyclerView recyclerView;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);


 recyclerView = (RecyclerView) findViewById(R.id.match_calender_recycler_view);

 recyclerView.setLayoutManager(new LinearLayoutManager(this));

 ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

 Call<;CalenderResponse>; call = apiService.getMatchCalender(API_KEY);
 call.enqueue(new Callback<;CalenderResponse>;() {
 @Override
 public void onResponse(Call<;CalenderResponse>; call, Response<;CalenderResponse>; response) {
 int statuscode = response.code();
 List<;MatchCalender>; matchlist = response.body().getData();
 recyclerView.setAdapter(new MatchCalenderAdapter(matchlist, getApplicationContext()));

 }

 @Override
 public void onFailure(Call<;CalenderResponse>; call, Throwable t) {
 Log.e(TAG, t.toString());
 }
 });
 }
}</pre>
<p><strong><span style="color: #008000;">Now when you run the app it will look like this: </span> </strong></p>
<p><img class="alignnone wp-image-1530" src="https://c1ctech.com/wp-content/uploads/2020/02/Screenshot_1580907706.png" alt="Screenshot_1580907706" width="438" height="778" />

