SlideShare a Scribd company logo
2
Most read
4
Most read
Retrofit Library in Android
Retrofit is REST API Client for Java.
It is developed by Square Inc. It uses OkHttp library for HTTP Request. It is a simple
library that is used for network transaction.
It is a very easy and fast library to retrieve and upload the data via Rest based web
service.
Adding Dependency in Build.gradle-
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}
Adding Internet Permission in Manifest-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kripashankar.countryappusingretrofit">
<uses-permission android:name="android.permission.INTERNET" />
Retrofit mainly need three things which are following-
1. Retrofit Instance-
You can create Retrofit instance by Retrofit.Builder().
You have to specify base url and converter factory at the time of Retrofit instance
creation as in the below example.
2. Interface -
public interface ApiCallInterface
{
@POST("api_name") // use @POST if api is post.
Call<CountryResponse> getResponseData();
}
3. Model Class-
Retrofit need a model class (POJO) for sending and receiving request.
Retrofit use the model class for parsing the server response by using convertors like
Gson, Jackson.
Example -
In below example, we are going to display country name and country code in
RecyclerView.
For which as in createRetroFitBuilder() method of example first we set header using
OkHttpClient class because API is authenticate api (set header only if api is
authenticate). Then we create Retrofit instance and set base url and converter factory
and call interface method which interact with API on background thread and
success of API can be get in onResponse() method of enqueue call back.Failure of
API can be get in onFailure() method of enqueue call back.After that pass the list of
country at adapter as in method setUpAdapterView() of example.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerViewCountry;
private CountryListAdapter countryListAdapter;
String BASE_URL = "http://example/retrofit/api/";
CountryResponse countryResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeView();
createRetroFitBuilder();
}
private void initializeView()
{
recyclerViewCountry = (RecyclerView)
findViewById(R.id.recyclerViewCountry);
}
private void createRetroFitBuilder() {
// set header through OkHttpClient if API is authenticate API.
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request request = chain.request().newBuilder()
.addHeader("timestamp", "153138130")
.addHeader("authentication_key",
"QJTpP/7rai7D7KF2RcNK=")
.build();
return chain.proceed(request);
}
});
// creating retrofit object and set base url , Converter factory
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
// calling of interface method which interact with API and give
response in onResponse().
ApiCallInterface apiCallInterface =
retrofit.create(ApiCallInterface.class);
Call<CountryResponse> call =
apiCallInterface.getResponseData();
call.enqueue(new Callback<CountryResponse>() {
@Override
public void onResponse(Call<CountryResponse> call,
Response<CountryResponse> response)
{
countryResponse = response.body();
setUpAdapterView();
}
@Override
public void onFailure(Call<CountryResponse> call, Throwable
t) {
Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).s
how();
}
});
}
private void setUpAdapterView() {
if(countryResponse != null)
{
countryListAdapter = new
CountryListAdapter(countryResponse,this);
LinearLayoutManager mLayoutManager = new
LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerViewCountry.setLayoutManager(mLayoutManager);
recyclerViewCountry.setAdapter(countryListAdapter);
}
}
}

More Related Content

PPT
Postman.ppt
PDF
Retrofit
PPTX
Chapter 3 servlet & jsp
PPTX
Understanding REST APIs in 5 Simple Steps
PDF
Nestjs MasterClass Slides
PPTX
Express JS
PPTX
Introduction to Spring Framework
 
PPTX
Java 8 Lambda and Streams
Postman.ppt
Retrofit
Chapter 3 servlet & jsp
Understanding REST APIs in 5 Simple Steps
Nestjs MasterClass Slides
Express JS
Introduction to Spring Framework
 
Java 8 Lambda and Streams

What's hot (20)

PPTX
Rest assured
PPTX
Android Services
PPTX
React hooks
PDF
Angular Observables & RxJS Introduction
PPTX
Servlets
PDF
What is REST API? REST API Concepts and Examples | Edureka
PPT
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
PDF
SOAP-based Web Services
PPTX
SignalR Overview
PDF
Spring Framework
PDF
PPTX
ReactJS presentation.pptx
PDF
Introduction to Redux
PDF
ES6 presentation
PPT
Jsp/Servlet
PPTX
REST API
PPTX
Introduction to java 8 stream api
PPTX
What is an API?
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
PPTX
REST & RESTful Web Services
Rest assured
Android Services
React hooks
Angular Observables & RxJS Introduction
Servlets
What is REST API? REST API Concepts and Examples | Edureka
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
SOAP-based Web Services
SignalR Overview
Spring Framework
ReactJS presentation.pptx
Introduction to Redux
ES6 presentation
Jsp/Servlet
REST API
Introduction to java 8 stream api
What is an API?
Workshop 4: NodeJS. Express Framework & MongoDB.
REST & RESTful Web Services
Ad

Similar to Retrofit library for android (13)

PPTX
Retrofit 2 - O que devemos saber
PDF
Lab 5-Android
PDF
Retrofit Android by Chris Ollenburg
PDF
Infinum Android Talks #01 - Retrofit
PDF
Extending Retrofit for fun and profit
PDF
Creating a Facebook Clone - Part XXVII - Transcript.pdf
PPTX
Retrofit Technology Overview by Cumulations Technologies
PDF
Advanced #2 networking
PDF
Creating a Facebook Clone - Part XXVII.pdf
PDF
Introduction to Retrofit
PDF
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
PPTX
Retrofit caching V1.9.0 - Android OkClient
PDF
Volley lab btc_bbit
Retrofit 2 - O que devemos saber
Lab 5-Android
Retrofit Android by Chris Ollenburg
Infinum Android Talks #01 - Retrofit
Extending Retrofit for fun and profit
Creating a Facebook Clone - Part XXVII - Transcript.pdf
Retrofit Technology Overview by Cumulations Technologies
Advanced #2 networking
Creating a Facebook Clone - Part XXVII.pdf
Introduction to Retrofit
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
Retrofit caching V1.9.0 - Android OkClient
Volley lab btc_bbit
Ad

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Machine learning based COVID-19 study performance prediction
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
MYSQL Presentation for SQL database connectivity
Big Data Technologies - Introduction.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectroscopy.pptx food analysis technology
Network Security Unit 5.pdf for BCA BBA.
Machine learning based COVID-19 study performance prediction
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Per capita expenditure prediction using model stacking based on satellite ima...
sap open course for s4hana steps from ECC to s4
Chapter 3 Spatial Domain Image Processing.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
MYSQL Presentation for SQL database connectivity

Retrofit library for android

  • 1. Retrofit Library in Android Retrofit is REST API Client for Java. It is developed by Square Inc. It uses OkHttp library for HTTP Request. It is a simple library that is used for network transaction. It is a very easy and fast library to retrieve and upload the data via Rest based web service. Adding Dependency in Build.gradle- dependencies { implementation 'com.squareup.retrofit2:retrofit:2.1.0' implementation 'com.google.code.gson:gson:2.6.2' implementation 'com.squareup.retrofit2:converter-gson:2.1.0' } Adding Internet Permission in Manifest- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.kripashankar.countryappusingretrofit"> <uses-permission android:name="android.permission.INTERNET" /> Retrofit mainly need three things which are following- 1. Retrofit Instance-
  • 2. You can create Retrofit instance by Retrofit.Builder(). You have to specify base url and converter factory at the time of Retrofit instance creation as in the below example. 2. Interface - public interface ApiCallInterface { @POST("api_name") // use @POST if api is post. Call<CountryResponse> getResponseData(); } 3. Model Class- Retrofit need a model class (POJO) for sending and receiving request. Retrofit use the model class for parsing the server response by using convertors like Gson, Jackson. Example - In below example, we are going to display country name and country code in RecyclerView. For which as in createRetroFitBuilder() method of example first we set header using OkHttpClient class because API is authenticate api (set header only if api is authenticate). Then we create Retrofit instance and set base url and converter factory and call interface method which interact with API on background thread and success of API can be get in onResponse() method of enqueue call back.Failure of API can be get in onFailure() method of enqueue call back.After that pass the list of country at adapter as in method setUpAdapterView() of example. public class MainActivity extends AppCompatActivity { private RecyclerView recyclerViewCountry; private CountryListAdapter countryListAdapter; String BASE_URL = "http://example/retrofit/api/"; CountryResponse countryResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeView(); createRetroFitBuilder(); } private void initializeView()
  • 3. { recyclerViewCountry = (RecyclerView) findViewById(R.id.recyclerViewCountry); } private void createRetroFitBuilder() { // set header through OkHttpClient if API is authenticate API. OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("timestamp", "153138130") .addHeader("authentication_key", "QJTpP/7rai7D7KF2RcNK=") .build(); return chain.proceed(request); } }); // creating retrofit object and set base url , Converter factory Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()) .build(); // calling of interface method which interact with API and give response in onResponse(). ApiCallInterface apiCallInterface = retrofit.create(ApiCallInterface.class); Call<CountryResponse> call = apiCallInterface.getResponseData(); call.enqueue(new Callback<CountryResponse>() { @Override public void onResponse(Call<CountryResponse> call, Response<CountryResponse> response) { countryResponse = response.body(); setUpAdapterView(); }
  • 4. @Override public void onFailure(Call<CountryResponse> call, Throwable t) { Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).s how(); } }); } private void setUpAdapterView() { if(countryResponse != null) { countryListAdapter = new CountryListAdapter(countryResponse,this); LinearLayoutManager mLayoutManager = new LinearLayoutManager(this); mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerViewCountry.setLayoutManager(mLayoutManager); recyclerViewCountry.setAdapter(countryListAdapter); } } }