The Retrofit library is a type-safe REST client for Android, Java, and Kotlin, developed by Square. With the help of the Retrofit library, we can have access to a powerful framework that helps us in authenticating and interacting with APIs and sending network requests with OkHttp. With the help of this library, downloading JSON or XML data from a web API becomes easy. In a Retrofit library, once the data is downloaded, it is parsed into a Plain Old Java Object (POJO) which must be defined for each “resource” in the response. Retrofit is an easy and fast library to retrieve and upload data via a REST-based web service.
Retrofit manages the process of receiving, sending, and creating HTTP requests and responses. It resolves issues before sending an error and crashing the application. It pools connections to reduce latency. It is used to cache responses to avoid sending duplicate requests.
Retrofit is very fast.
Retrofit enables direct communication with the web service.
Retrofit supports dynamic URLs.
Retrofit is easy to use and understand.
Retrofit supports both synchronous and asynchronous network requests.
Retrofit supports converters.
Retrofit supports request cancellation.
Retrofit supports post requests and multipart uploads.
Retrofit does not support setting priorities.
Retrofit does not support image loading.
Retrofit requires other libraries such as Glide and Picasso.
Model Class: A model class contains the objects to be obtained from the JSON file.
Retrofit Instance: This is a Java class. It is used to send requests to an API.
Interface Class: This is a Java class. It is used to define endpoints.
Example:
To use Retrofit we go through the following steps:
Step 1: In this step first we will create a new Android project in Android studio.
Step 2: Dependencies
In our project, add the following dependencies in the build.gradle file.
1 2 3
implementation 'com.squareup.retrofit2:retrofit:2.7.2' implementation 'com.squareup.retrofit2:converter-gson:2.7.2' implementation 'com.squareup.okhttp3:okhttp:3.6.0'
Step 3: Permission
We need to add internet permission in AndroidMinfest.xml.
1
<uses-permission android:name="android.permission.INTERNET"/>
Step 4: activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="@color/white"> <ListView android:id="@+id/superheroes_list" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Step 5:
We will create a model class.
Model.java
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Model {
@SerializedName("name")
private String superName;
public Model(String name) {
this.superName = name;
}
public String getName() {
return superName;
}
}
Step 6:
In this step, we create a Retrofit instance of the Java class. This class specifies the URL that contains the data required and uses the Retrofit Builder class.
RetrofitClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private static RetrofitClient instance = null;
private Api myApi;
private RetrofitClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
myApi = retrofit.create(Api.class);
}
public static synchronized RetrofitClient getInstance() {
if (instance == null) {
instance = new RetrofitClient();
}
return instance;
}
public Api getMyApi() {
return myApi;
}
}
Step 7:
In this step, we define an endpoint inside an interface class.
Api.java
1
2
3
4
5
6
public interface Api {
String BASE_URL = "https://simplifiedcoding.net/demos/";
@GET("marvel")
Call < List < Model >> getsuperHeroes();
}
Step 8:
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class MainActivity extends AppCompatActivity {
ListView superListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
superListView = findViewById(R.id.superheroes_list);
getSuperHeroes();
}
private void getSuperHeroes() {
Call < List < Model >> call = RetrofitClient.getInstance()
.getMyApi()
.getsuperHeroes();
call.enqueue(new Callback < List < Model >> () {
@Override
public void onResponse(Call < List < Model >> call, Response < List < Model >> response) {
List < Model > myheroList = response.body();
String[] oneHeroes = new String[myheroList.size()];
for (int i = 0; i < myheroList.size(); i++) {
oneHeroes[i] = myheroList.get(i)
.getName();
}
superListView.setAdapter(new ArrayAdapter < String > (getApplicationContext(), android.R.layout.simple_list_item_1, oneHeroes));
}
@Override
public void onFailure(Call < List < Results >> call, Throwable t) {
Toast.makeText(getApplicationContext(), "An error has occured", Toast.LENGTH_LONG)
.show();
}
});
}
}
Output: