How to get JSON object via API call using Retrofit

Hello and happy New year!
Today we will learn how to pull JSON data from remote server using Retrofit and API calls.

This is the JSON object of my profile from github:
https://api.github.com/users/azemZejnil/repos
Lets say I want to get some of the details from JSON. Retrofit is really good way to do that. It takes care of all threading stuff.
To implement Retrofit, first we must import dependencies. In your build.gradle(Module.app), add these lines in dependencies{}:

build.gradle(Module:app)
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Next, we have to make an interface with all the methods we plan to use. Create an interface called RetrofitClient:

RetrofitClient.class
import java.util.List;

import retrofit2.Call;
import retrofit2.http.Path;
import retrofit2.http.GET;

/**
 * Created by azem on 1/1/18.
 */

public interface RetrofitClient {
         //https://api.github.com/users/azemZejnil/repos is whole URL

     //"users/{user}/repos" is the part of URL will be added to base URL. 
    @GET("users/{user}/repos")
    //List<GithubRepo> is return type    @Path("user")String user is the parameter we will pass           
    Call<List<GithubRepo>> reposForUser(@Path("user")String user);
}

In RetrofitClient, we defined reposForUser() method. @GET means we are getting data from server (and not POSTing).

/{user}/ means we can change the name of desired user dinamically by passing ‘user’ parameter.

Next, lets create the model class for our response. Inside of it you can add as many fields which are contained in JSON. I wanted to get a name, full_name and some Owner details. For that, I also had to make an Owner class. I made an internal class Owner:

GithubRepo.class
public class GithubRepo {
    
    // fields must have same names as fields in JSON. watch out!
    private String name;
    private String full_name;
    private Owner owner;

    public String getName() {
        return name;
    }

    public String getFull_name() {
        return full_name;
    }


    public Owner getOwner() {
        return owner;
    }


    public class Owner {
        public String login;
        public int id;

        public String getLogin() {
            return login;
        }

        public int getId() {
            return id;
        }
    }

}

We will display names in ListView in our MainActivity. Lets create an adapter for ListView:

GitHubRepoAdapter.class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class GitHubRepoAdapter extends ArrayAdapter<GithubRepo> {

    private Context context;
    private List<GithubRepo> values;

    public GitHubRepoAdapter(Context context, List<GithubRepo> values) {
        super(context, android.R.layout.simple_list_item_1, values);

        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.list_item_pagination, parent, false);
        }

        TextView textView = (TextView) row.findViewById(R.id.list_item_pagination_text);

        GithubRepo item = values.get(position);
        String message = item.getName();
        textView.setText(message);

        return row;
    }
}

This is activity_main layout:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.notifications.youtube.azem.virtuoozatutorials.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</android.support.constraint.ConstraintLayout>

And finally, in MainActivity we set up an RetrofitClient and call the method for getting the response:

MainActivity.class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private ListView listView;

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

        listView= (ListView)findViewById(R.id.listView);

        Retrofit.Builder builder =new Retrofit.Builder()
                         //this is the base URL. URL we created in interface will be added to it
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit = builder.build();

        RetrofitClient client = retrofit.create(RetrofitClient.class);
                                     //this is where we call the method fromRetrofitClient. 
                                     // I passed my ID from github for getting data. Try your own
        Call <List<GithubRepo>>call =client.reposForUser("azemZejnil");

        call.enqueue(new Callback<List<GithubRepo>>() {
            @Override
            public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
                List<GithubRepo>repos= response.body();
                // this is where we handle the response ofc
                listView.setAdapter(new GitHubRepoAdapter(MainActivity.this,repos));
            }

            @Override
            public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
                Toast.makeText(MainActivity.this,"Something wrong",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Share with your friends
Tagged with: