Retrofit Android Example – Fetching JSON from URL

Hey guys, so here is a Retrofit Android Example for you. In this post, we will learn to fetch JSON data from a given URL.

What is Retrofit?

You might be knowing that in almost every Android project we need to work with APIs, which is nothing but an HTTP call to a particular URL. And we have already done this thing in some previous posts, an example you can see from the below-given link.

Android JSON Parsing using AsyncTaks

If you have been through the above post, then you know how much code we need to write for the network operation. And at the same time, we need to take care of a hell lot of things, like memory, cache, etc. So to make the life easier we have some libraries that can simplify our task. And Retrofit is one of the most popular used libraries for this job.

The API

The URL that gives us some data or to some task upon sending an HTTP request is called an API. And for this example, I already have an API, so you do not need to create the API. Below is our API URL.

https://simplifiedcoding.net/demos/marvel/

If you go to the above URL, you will get a response as shown below.

I hope you know about the JSON. So the response we are getting from the above URL is a JSON Array []. If you want to know how to make an API, you can see a detailed post about it from the link given below.

Build REST API using Laravel Lumen for your Application

Now our task is to fetch and parse the above JSON data in our Android Application using the Retrofit Library. So let’s begin.

Retrofit Android Example

Creating a new Project

  • Lets first create a new Android Studio Project. I have created a project named RetrofitExample.
  • Once the project is created we need to add the following two libraries to our project.
    • Retrofit -> For the network calls
    • Gson -> For easy parsing of JSON data

Adding Retrofit and Gson

  • Adding libraries are very easy. You just need to add the following two lines inside the dependencies block of your app level build.gradle file.

  • You also need to add Java8 compileOptions . Do it inside android  block.

  • Now just sync your project and you are done.

Creating API Interface

  • To make an API call using retrofit we need a java interface where we define all the URLs with the http request type and parameters. In this example we need to perform an http GET with no extra parameters.
  • So lets create a java interface inside and name it Api.java (You can name it anything you want).

  • As you can see we have a very simple interface above. Inside the interface first we have a BASE_URL. It contains the ROOT URL of our API. For any project we make an API like myproject/api/v1/apiname. Retrofit divides it in two parts the first part is the base URL and then the api name. So in our example marvel is the api name and before it we have the BASE URL
  • After the base URL we have an annotation @GET(“marvel”). It means that we are defining an http GET request. And the String passed inside the get is the api name. So for this GET it will make the complete URL joining the BASE_URL and the api name.
  • Then we have a method named getHeroes() whose return type is Call. And the type of the Call is a List<>. And type of the List is Hero. It may sounds confusing but it is not. Actually we need to structure the api call according the the response. So our URL is giving us an json array and that is nothing but a list of heroes. So we defined the Call type as a List and the List type as Hero. Now we need to define the Hero class.

The Model Class

  • Lets create a class named Hero. It will be a simple java class with a constructor and getters. And inside this class we will define all the attributes of our response.

  • Make sure your variable names matches with the JSON attributes. As we have the following JSON objects in our response.

  • So for getting this name we have to name our String as name (case sensitive) in the model class. Now if you want to make different names then you can define your model class as below.

  • So if you put the annotation @SerializedName(“attribute name”) with the json attribute name just above every variable you are defining, you can name your variables anything but you have to put the correct attribute name inside SerializedName(“name”).

Creating Singleton Retrofit Client

If your application uses frequent network calls, then you must create a Singleton Instance of Retrofit. Because creating Retrofit instance every-time when you need to perform a network request is not a good idea.

  • Now to get our API instance we can simply call RetrofitClient.getInstance().getMyApi()  and then we can call the function getHeroes()  to make a request to our API.

Making the API Call

  • Now the final step is performing the API call. It is also very easy.

  • Now let’s do it in our project.

Displaying the Heroes in a ListView

Creating Interface

  • Come inside activity_main.xml of your project and create a ListView.

Fetching the JSON Data

  • Now inside MainActivity.java write the following code.

Adding Internet Permission

  • As we are performing a network operation, internet permission is needed. So inside your AndroidManifest.xml define the internet permission.

  • Thats it now you can play your application.
retrofit android example
Retrofit Android Example
  • Bingo! it is working absolutely fine.

Displaying the Heroes in a RecyclerView

  • Here I showed only the hero names in a simple ListView, but you can use all the attributes to display. If you are confused how to do this? Here is one more tutorial doing the same with the volley. So once you got the List of heroes in your app, you can implement the process shown here.

Expandable RecyclerView Android – RecyclerView with Expandable Items

  • I am using the same api in the link given above so you have to exactly the same thing to display the data in a RecyclerView.

Retrofit Android Example Source Code

  • If you are still confused you can get my source code from the link given here.

So that’s all for this Retrofit Android Example friends. Hope you liked it. So if you think it helped you then you, please help us by SHARING this post. Thank You 🙂

30 thoughts on “Retrofit Android Example – Fetching JSON from URL”

  1. Hi Belal
    Thanks for sharing this tutorial, its help me a lot,
    i have a little query that how can i fetch JSON that stored on unique id like mobileno or email

    thanks in advance.

    Reply
  2. nice tutorial. But i gt a problem. Logs are showing the name of heroes and their real names.But list is not showing anything only 5 blank rows

    Reply
  3. Hi Man, Its a Best tutorial for beginners. It was very helpful. Keep up posting more about interface usage in android. It will be helpful for me. Thanks in advance…..

    Reply
  4. Hi Belal
    Thanks for sharing this tutorial, its help me a lot,
    i have a little query that how can i fetch nested JSON data with retrofit.
    Thank you

    Reply
  5. Bro , you are a pro.
    Thank you for all the efforts you are putting in making these tutorials. These step by step guide is so helpful for beginners like us.
    Keep posting more.

    Reply
  6. Hi all,
    I am facing issues as below like,

    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Api.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create()).build();

    error : Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

    if I am change the code as below like then i am getting different error as below,

    Gson gson = new GsonBuilder() .setLenient() .create();
    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Api.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson)).build();
    error:

    Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

    Please help me.

    Reply
  7. it worked if the api has an array [] instead of an object {} how can we handle it if it is an object obviously you use List because it an array but it does not work for object please someone should help me out

    Reply

Leave a Comment