Retrofit— A simple Android tutorial
For this tutorial, we are going to see how to use Retrofit HTTP client in your Android application.
Retrofit is an awesome type-safe HTTP client for Android and Java built by awesome folks at Square. Retrofit makes it easy to consume JSON or XML data which is parsed into Plain Old Java Objects (POJOs).
If you just want to get the sample project, then you can find it here.
So, without any further delays, lets 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.
3. Don’t forget to add INTERNET permissions in AndroidManifest.xml file like this
4. Next, we will create data model to parse our sample JSON data with following structure.
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.
And that’s it. Thank you for sticking with me till the end of this tutorial. I hope this was helpful in some way to you.
Till next time :) Happy Learning.
If you liked this article make sure to 👏 it below, and follow me on twitter!
If you would like to support me, please consider buying me a cuppa