Starter Guide to Retrofit - Android Studio- Part four

Starter Guide to Retrofit - Android Studio- Part four

Setting up the retrofit builder and the View to display our loaded data.

Welcome to our fourth and final beginner guide to retrofit in Android Studio, Please check out my previous posts to follow along.

This is the part that will actually allow the HTTP call using the base URL. We will first set up our View to be ready to display our data.

The layout should look close to something like this.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/company_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name_text_view" />

    <TextView
        android:id="@+id/blog_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/company_text_view" />

    <TextView
        android:id="@+id/location_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/blog_text_view" />

    <TextView
        android:id="@+id/bio_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/location_text_view" />

</androidx.constraintlayout.widget.ConstraintLayout>

We will then have to declare our view objects on the main activity.

TextView name,company,blog,location, bio;

Once we have set up the text view

        name = findViewById(R.id.name_text_view);
        company = findViewById(R.id.company_text_view);
        blog = findViewById(R.id.blog_text_view);
        location = findViewById(R.id.location_text_view);
        bio = findViewById(R.id.bio_text_view);

We will now make the retrofit builder. We will now need the base URL that we had isolated in the previous part of this guide. The Retrofit library will take the base URL and use the GET method to append the query params part and make the relative URL. This is also where we will use the GSON converter that we had installed in our package.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://run.mocky.io") // Base URL
                .addConverterFactory(GsonConverterFactory.create()) //GSON library
                .build();

Let us not forget to add permission into our manifest file

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

We will then need to create an instance for the API.

           //Instance for the interface.
        ApiCall apiCall = retrofit.create(ApiCall.class);

We have to instantiate the actual API call. (the getData Method does the actual API calling.)

Call<ProfileModel> call = apiCall.getData();

In order to use the call, we need to queue it to a thread, that is not running in the main thread. In the "onResponse" call, we get into it by first making a check for the response. This is achieved using an if, that takes note of the HTTP response code, as detailed in the logic below.

call.enqueue(new Callback<ProfileModel>() {
            @Override
            public void onResponse(Call<ProfileModel> call, Response<ProfileModel> 
                response) {
                if(response.code() != 200){
                    name.setText("Unable to establish connection.Please try again later");
                    return;
                }
                name.append("My name is " + response.body().getName());
                company.append("I work at " + response.body().getCompany());
                blog.append("Find our work at " + response.body().getBlog());
                location.append("I am statined in " + response.body().getLocation());
                bio.append("I server as a: " + response.body().getBio());

            }

            @Override
            public void onFailure(Call<ProfileModel> call, Throwable t) {

            }
        });

This automatically passes the data Model we had created, auto-generates the callbacks, with the call to on failure.

At this point, your Activity class should be something like this.


public class MainActivity extends AppCompatActivity {

    TextView name,company,blog,location, bio;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.name_text_view);
        company = findViewById(R.id.company_text_view);
        blog = findViewById(R.id.blog_text_view);
        location = findViewById(R.id.location_text_view);
        bio = findViewById(R.id.bio_text_view);

        //The retrofit builder

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://run.mocky.io")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //Instance for the interface.
        ApiCall apiCall = retrofit.create(ApiCall.class);
        Call<ProfileModel> call = apiCall.getData();
        call.enqueue(new Callback<ProfileModel>() {
            @Override
            public void onResponse(Call<ProfileModel> call, Response<ProfileModel> response) {
                if(response.code() != 200){
                    name.setText("Unable to establish connection.Please try again later");
                    return;
                }
                name.append("My name is " + response.body().getName());
                company.append("I work at " + response.body().getCompany());
                blog.append("Find our work at " + response.body().getBlog());
                location.append("I am statined in " + response.body().getLocation());
                bio.append("I server as a: " + response.body().getBio());

            }

            @Override
            public void onFailure(Call<ProfileModel> call, Throwable t) {

            }
        });
    }
}

Congratulations. You have just loaded Data via retrofit into your Android studio App. Stay tuned for more guides.

Find our current retrofit guides here.