Retrofit Android Tutorial

In this tutorial, we are going to see Retrofit Android tutorial to get data from server.
In previous post, we have seen android JSON parsing tutorial which was very simple.
If you are not aware about Retrofit, it is android http library used to handle HTTP request.You can treat it as a replacement of AsyncTask in previous tutorial.

Why to use Retrofit rather than Volley or AsyncTask.

It is better than Volley and AsyncTask. It takes care of HTTP call, JSON parsing, efficient network management. Retrofit has all the features which you need to call web services. You will directly get Response which you can use to populate data.

Example :

I have already implemented restful webservices json example. I am going to use same json response for rendering it in custom listview.
You can use below link.
https://cdn.rawgit.com/arpitmandliya/AndroidRestJSONExample/master/countries.json
You will get below Json response from above URL:

We are getting above JSONArray from rest web service. If you are not familiar with JSON, you can go through Json tutorial. We are going to render above JSON response to android custom listview as below:

Lets code this example now:

Source code:

Step 1 :Creating Project

Create an android application project named “RetrofitAndroidExample”.

Step 2 : Add Retrofit and json gradle dependency

For using Retrofit library, we need to add Retrofit and volley dependency. Your build.gradle (Module : app )will look as below

Step 3 : Creating Layout

Change res ->layout -> activity_main.xml as below:

We have one button and listview. When you click the button, we are going to populate data in listview by calling restful web services and render it on the listview.

Step 4: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File.
  • Create a file named “row_item.xml” and paste below code in row_item.xml.

Step 5 : Creating model object Country :

If you notice, we are getting Json array from restful web service which has 4 items. Each item have two attributes id and countryName. We are going to create country object for each item.

Step 6:  Creating BaseAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
This class is used to populating data for ListVIew. getView method is get called for drawing each row.

Step 7 : Creating interface for making HTTP call using Retrofit.

We need to create an interface for making HTTP calls.
We have defined get request in above interface. We do not have to include base url, it is part after base url which we have use. We are going to get List of countries as response here.

Step 8 : Creating MainActivity

Steps for Retrofit call :

  • Create retrofit instance using base url. Retrofit will implicitly use gson to convert JSON to corresponding object. You need to define gson library explicitly in Retrofit 2.0
  • Create api with retrofit’s create method and call getCountries method.
  • Enqueue the request and onResponse will get called if your call is successful else onFailure will get called.

Change src/main/packageName/MainActivity.java as below:

Step 8: Add internet permission in AndroidManifest.xml

Copy following code:

Put it in AndroidManifest.xml

Done, we have added internet permission to AndroidManifest.xml. Your application must be able to access internet now.

Step 9 : Running the app

When you run the app, you will get below screen:

When you click on above button, you will get below screen.

We are done with Android Retrofit tutorial. If you are facing any issue, please comment.

Was this post helpful?

Related Posts

  • 02 December

    Pass Variable From PHP to JavaScript

    Table of ContentsUse echo methodUse json_encode methodUse htmlspecialchars method Use echo method In order to pass variable from PHP to JavaScript, you will need to use the echo statement. This will print out the variable for you. For example, if you have a variable named $name, you would use the following code: [crayon-638b3ee0254d7316621362/] This will […]

  • 02 December

    Remove Quotes from String in PHP

    Table of ContentsRemove Quotes from String in PhpUsing str_replace() MethodUsing preg_replace() MethodRemove Quotes from Beginning and End of String in PhpUsing trim() MethodUsing preg_Replace() Method Remove Quotes from String in Php Using str_replace() Method Use the str_replace() function to remove quotes from String in PHP. [crayon-638b3ee025678006330424/] [crayon-638b3ee02567c341382480/] We used str_replace() to remove double quotes and […]

  • 30 November

    Check if Array is Empty in PowerShell

    Table of ContentsWhat is an Empty Array?Use the Count Property to Check If an Array is Empty in PowerShellUse the Length Property to Check If an Array is Empty in PowerShell 💡TL;DR To check if an array is empty access its count property e.g. arr.count. If count is equal to 0, then array is empty. […]

  • 30 November

    Split Integer into Digits in Python

    Table of ContentsUsing List ComprehensionUsing for LoopUsing map() with list() & str.split() Using List Comprehension To split integer into digits in Python: Use the str() to transform the specified integer to a string. Use a list comprehension to loop over converted String. Use int() to convert every substring to an integer in each iteration. [crayon-638b3ee0258d9340250663/] […]

  • 29 November

    Get Length of String in PowerShell

    Table of ContentsUsing String’s Length propertyUsing Measure-Object with Character parameter Using String’s Length property Use string’s length property to get length of String in PowerShell e.g. "Hello World".Length. System.String‘s Length property returns number of Characters present in the String. [crayon-638b3ee0259f2617524987/] Output [crayon-638b3ee0259f5113403721/] Here, we declared a string variable blog_Name which contains string Java2blog. We have […]

  • 29 November

    Prefix b Before String in Python

    Table of ContentsPrefix b Before String in PythonConclusion Prefix b Before String in Python Prefix b before String denotes a byte String. By putting b before String, you can convert String to bytes in Python. The upgrade from Python 2 to Python 3 was considered a major change as many new features were introduced and […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.