Simple GET request using Retrofit in Android

Retrofit could be a type-safe HTTP networking library used for Android and Java. The retrofit was even better since it absolutely was super fast, offered better functionality, and even simpler syntax. Most developers since then have switched to using Retrofit to form API requests.

Uses of retrofit

Retrofit is used to perform the following tasks:

  • It manages the method of receiving, sending, and creating HTTP requests and responses.
  • It alternates IP addresses if there’s a connection to an online service failure.
  • It caches responses to avoid sending duplicate requests.
  • Retrofit pools connections to scale back latency.
  • Retrofit resolves issues before sending a blunder and crashing the app.

Advantages of retrofit

  • It is very fast.
  • It enables direct communication with the online service.
  • It is easy to use and understand.
  • It supports request cancellation.
  • It supports post requests and multipart uploads.
  • It supports both synchronous and asynchronous network requests.
  • Supports dynamic URLs.
  • Supports convertors.

Disadvantages of retrofit

  • It doesn’t support image loading. It requires other libraries like Glide and Picasso.
  • It doesn’t support setting priorities.

Classes used in retrofit

  • Model class – The retrofit class contains objects to be obtained from the JSON file.
  • Retrofit instance – This Java class is employed to send requests to an API.
  • Interface class- This Java class is employed to define endpoints.

Prerequisites

  • Have Android Studio installed.
  • The reader should have a First-level understanding of Java and XML.
  • The reader should have basic knowledge of constructing network requests for JSON, and REST APIs.

Step 1 – Create a new Android studio project

Open Android Studio and start a new Project. The project name is RetrofitDemoApp.

Step 2 – Adding retrofit dependencies

Add the following dependencies to build.gradle file.

implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'

Note: Add different converters depending on the JSON one would like to use:

Jackson : com.squareup.retrofit2:converter-jackson:2.1.0
Moshi : com.squareup.retrofit2:converter-moshi:2.1.0
Protobuf : com.squareup.retrofit2:converter-protobuf:2.1.0
Wire : com.squareup.retrofit2:converter-wire:2.1.0
Simple XML : com.squareup.retrofit2:converter-simplexml:2.1.0

Add internet permission to your app.

<uses-permission android:name="android.permission.INTERNET" />

Step 3 – Designing the UI for our application

In this step, we will design the layout for our app. We will only use a ListView to display the API’s information.

Add the following lines of code to your layout res file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@color/white">

    <ListView
        android:id="@+id/lvView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Step 4 – Create a model class

In the Java directory, right-click and select the new class. We will name our model class Results.

Add the following lines of code in Results.Java:

public class Results {

    @SerializedName("name")
    private String superName;


    public Results(String name) {
        this.superName = name;
    }

    public String getName() {
        return superName;
    }
}

Note: The SerialzedName annotation should always display the exact name of an object in the JSON file.

Step 5 – Create a retrofit instance

In the Java directory, right-click and select new class. We shall name our class, RetrofitClient.

Add the following lines of code to the RetrofitClient.Java:

public class RetrofitClient {

    private static RetrofitClient instance = null;
    private Api myApi;

    private RetrofitClient() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        myApi = retrofit.create(Api.class);
    }

    public static synchronized RetrofitClient getInstance() {
        if (instance == null) {
            instance = new RetrofitClient();
        }
        return instance;
    }

    public Api getMyApi() {
        return myApi;
    }
}

Step 6 – Define the endpoints

In the Java directory, right-click and select new class. We will name our Interface class RetroInterFace.

Add the following lines of code in RetroInterFace.Java :

public interface RetroInterFace {

    String BASE_URL = "https://simplifiedcoding.net/demos/";
    @GET("marvel")
    Call<List<results>> getsuperHeroes();
}

Step 7 – Sending a GET request

Finally, we will have an onFailure method, that will display a Toast message if the information is not successfully loaded into the ListView.

Add the following lines of code to your MainActivity.Java :

public class MainActivity extends AppCompatActivity {

    ListView superListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        superListView = findViewById(R.id.lvView);

        getSuperHeroes();
    }

    private void getSuperHeroes() {
        Call<List<Results>> call = RetrofitClient.getInstance().getMyApi().getsuperHeroes();
        call.enqueue(new Callback<List<Results>>() {
            @Override
            public void onResponse(Call<List<Results>> call, Response<List<Results>> response) {
                List<Results> myheroList = response.body();
                String[] oneHeroes = new String[myheroList.size()];

                for (int i = 0; i < myheroList.size(); i++) {
                    oneHeroes[i] = myheroList.get(i).getName();
                }

                superListView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, oneHeroes));
            }

            @Override
            public void onFailure(Call<List<Results>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "An error has occured", Toast.LENGTH_LONG).show();
            }

        });
    }
}

That is it!

Let’s run our application.

Submit a Comment

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

Subscribe

Select Categories