Retrofit is a type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services. … Retrofit automatically serializes the JSON response using a POJO(Plain Old Java Object) which must be defined in advance for the JSON Structure.
Let's get started by first creating a new project in Android Studio.
- Go to File ⇒ New Project. When it prompts you to select the default activity, select Empty Activity and proceed.
- Open build.gradle in (Module:app) and add Retrofit, Picasso, RecyclerView, Gson dependencies like this.
- Don’t forget to add INTERNET permissions in AndroidManifest.xml file like this
- Next, we will create data model to parse our sample JSON data with following structure.
Sample JSON data
Create a class named RetroPhoto.java under model package like this.
5. Create the Retrofit Instance
To issue network requests to a REST API with Retrofit, we need to create an instance using the Retrofit.Builder
class and configure it with a base URL.
Create a class RetrofitClientInstance.java under network package. Here BASE_URL is the basic URL of our API where we will make a call.
6. Define the Endpoints
The endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method.
7. Create custom adapter for binding data with RecycleView.
Create a class named CustomAdapter.java under adapter package like this.
7. Final step
Inside the onCreate() method of the MainActivity.java, we initialize an instance of the GetDataService interface (line 16), the RecyclerView, and also the adapter. Finally, we call the generateDataList() method.
8. Understanding enqueue()
enqueue()
asynchronously sends the request and notifies your app with a callback when a response comes back. Since this request is asynchronous, Retrofit handles it on a background thread so that the main UI thread isn't blocked or interfered with.
To use enqueue()
, you have to implement two callback methods:
onResponse()
onFailure()
9. Fire up the app
Finally, you can fire up the app and see a nice list like this.
That’s how e integrated an API using retrofit in our app. keep coding