SlideShare a Scribd company logo
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

PPTX
Introduction to Android ppt
PPT
International Space Station
 
PPTX
Android PPT
PDF
Android Platform Architecture
PPT
Simple Java Programs
PPTX
Space x ppt
PPTX
Android Operating System
PPTX
Android - Graphics Animation in Android
Introduction to Android ppt
International Space Station
 
Android PPT
Android Platform Architecture
Simple Java Programs
Space x ppt
Android Operating System
Android - Graphics Animation in Android

What's hot (20)

PPTX
Satellites launched by india
PPTX
Space Missions Design and Operations
PDF
Android tutorial ppt
PPT
Chandrayaan
PPTX
Voyager 1
PPTX
07 java variables
PPTX
Chandrayaan 1
PDF
Scala in a nutshell
PDF
Artificial Intelligence In Astronomy
PDF
Java vs kotlin
PPT
Mangalyaan
PPT
Early History Of Spacecraft
DOCX
SPACE IN INDIA
PPTX
Buzzer Part 1
PPTX
Day: 1 Introduction to Mobile Application Development (in Android)
PDF
Android Operating System (Androrid OS)
PDF
Mars 2020
PPT
CHANDRAYAN
PPTX
Space tourism presentation
Satellites launched by india
Space Missions Design and Operations
Android tutorial ppt
Chandrayaan
Voyager 1
07 java variables
Chandrayaan 1
Scala in a nutshell
Artificial Intelligence In Astronomy
Java vs kotlin
Mangalyaan
Early History Of Spacecraft
SPACE IN INDIA
Buzzer Part 1
Day: 1 Introduction to Mobile Application Development (in Android)
Android Operating System (Androrid OS)
Mars 2020
CHANDRAYAN
Space tourism presentation
Ad

Similar to Retrofit Library In 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

More from InnovationM (20)

PDF
How to use data binding in android
PDF
Capture image on eye blink
PDF
Mob x in react
PDF
How to use geolocation in react native apps
PDF
Android 8 behavior changes
PDF
Understanding of react fiber architecture
PDF
Automatic reference counting (arc) and memory management in swift
PDF
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
PDF
How prototype works in java script?
PDF
React – Let’s “Hook” up
PDF
Razorpay Payment Gateway Integration In iOS Swift
PDF
Paytm integration in swift
PDF
Line Messaging API Integration with Spring-Boot
PDF
Basic fundamental of ReactJS
PDF
Basic Fundamental of Redux
PDF
Integration of Highcharts with React ( JavaScript library )
PDF
Serialization & De-serialization in Java
PDF
Concept of Stream API Java 1.8
PDF
How to Make Each Round of Testing Count?
PDF
Model View Presenter For Android
How to use data binding in android
Capture image on eye blink
Mob x in react
How to use geolocation in react native apps
Android 8 behavior changes
Understanding of react fiber architecture
Automatic reference counting (arc) and memory management in swift
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
How prototype works in java script?
React – Let’s “Hook” up
Razorpay Payment Gateway Integration In iOS Swift
Paytm integration in swift
Line Messaging API Integration with Spring-Boot
Basic fundamental of ReactJS
Basic Fundamental of Redux
Integration of Highcharts with React ( JavaScript library )
Serialization & De-serialization in Java
Concept of Stream API Java 1.8
How to Make Each Round of Testing Count?
Model View Presenter For Android

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Machine learning based COVID-19 study performance prediction
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
A Presentation on Artificial Intelligence
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
cuic standard and advanced reporting.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Machine learning based COVID-19 study performance prediction
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity
A Presentation on Artificial Intelligence
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
Chapter 3 Spatial Domain Image Processing.pdf
A comparative analysis of optical character recognition models for extracting...
cuic standard and advanced reporting.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
sap open course for s4hana steps from ECC to s4
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Programs and apps: productivity, graphics, security and other tools
“AI and Expert System Decision Support & Business Intelligence Systems”
Unlocking AI with Model Context Protocol (MCP)
Dropbox Q2 2025 Financial Results & Investor Presentation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Retrofit Library In 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); } } }