Working with Retrofit (part 1)
Hey! if you are seeing this, most probably you may have web services in your mind. Well this is very basic thing. While developing a mobile application if we want to fetch some data from the server, We have to call webservices and they return some kind of data in the form of either JSON(mostly) or XML.
Now Android gives many ways to call a webservice API, first ways we can go with the basic code given by Android from starting version using HttpURLConnection which is very time consuming and of-course not that much easy, or we can use any third party library such as Retrofit by Square, Volley by Google, Ion and etc.
You can use any method but personally i prefer Retrofit over any other.
Before using Retrofit in your Android App project, lets configure it by following simple steps.
Add the below dependencies in your app level build.gradle file.
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
Lets assume, you want to call a login API that accepts username and password. See the below image.
And this API returns result as follows
Step 1) Create a Factory class that’ll give you the same Retrofit object whenever you ask for it.
Step 2) Define a Pojo class into which JSON data will be parsed automatically by Retrofit.
Step 3) Define an interface having method to login as follows. Note all API calls will be represented by each method.
Step 4) Call this method when you want to login.
Step 5) Define callback methods to be called when API sends response.
Congratulations! you’ve successfully called your API by retrofit.
The best thing i have observed with Retrofit is that you don’t need to parse that JSON response explicitly which is really very time consuming as it may have a lot of nested loops. As for now our login response is returning very few key-value pairs in JSON. But just call google provided NearByPlace api which returns huge JSON data, that time your Retrofit will be your true friend.
for more features of Retrofit please see Working with Retrofit (part 2)
That’s it for now, and yes if you like the content, please clap. It really matters :)