Retrofit 2 Tutorial

Retrofit is one of the most popular REST client library for android developed by Square . For HTTP requests, retrofit uses OkHttp library. Also we can process the return values easily using custom converters. Following converters are supported by Retrofit : 

Gson: com.squareup.retrofit2:converter-gson

Jackson: com.squareup.retrofit2:converter-jackson

Moshi: com.squareup.retrofit2:converter-moshi

Protobuf: com.squareup.retrofit2:converter-protobuf

Wire: com.squareup.retrofit2:converter-wire

Simple XML: com.squareup.retrofit2:converter-simplexml

Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

In this tutorial, we will make one request to the Github Api,GET THE RETURN JSON VALUES using retrofit , and finally we will convert these json values using json converter.

API Request :
As mentioned above, we are making a request to GitHub public api to get list of all repositories.

Response Type : 

Response type will be JSON. You can use online JSON Viewer tool like this to see how it looks like.


JSON Objects are written inside curly braces “{}” and JSON arrays are written inside square brackets “[]” . i.e. our return type is a JSON array containing JSON objects. 

Each JSON objects looks like :


We will extract only “name” of each JSON object. 
  1. Create a simple Android application on Android Studio.
  2. Gradle Dependencies : Add the following dependencies to your build.gradle file :

    compile ''
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  3. Add internet permission inside your AndroidManifest.xml file :
    <uses-permission android:name="android.permission.INTERNET"/>
  4.  We need 3 classes mainly to work with Retrofit :
    1. One Model class to map JSON data.
    2. One Interface class to define network operations.
    3. One instance of Retrofit.Builder class . This instance will use the instance of the interface class to make a call. 
  1. Model Class:
    Create one class as below :

    public class GitRepoModel {
        private String name;
        public String getName(){
            return name;

     As we are getting only “name” of each JSON object, only one variable is defined here.

  2. Interface Class :
    Create one Interface class as as below :

    import java.util.List;
    import retrofit2.Call;
    import retrofit2.http.GET;
    import retrofit2.http.Path;
    public interface APIService {
        Call<List<GitRepoModel>> getRepos(@Path("user") String user);

     Note : As we are getting an array of JSON Objects, "List<GitRepoModel>"is used in this example.

  3. Change your as below  :

    public class MainActivity extends AppCompatActivity implements Callback<List<GitRepoModel>> {
        private static final String ENDPOINT = "";
        private static final String TAG = "RETRODEMO";
        protected void onCreate(Bundle savedInstanceState) {
            Gson gson = new GsonBuilder()
            Retrofit retrofit = new Retrofit.Builder()
            APIService githubUserAPI = retrofit.create(APIService.class);
            Call<List<GitRepoModel>> call = githubUserAPI.getRepos("codevscolor");
            //asynchronous call
        public void onResponse(Call<List<GitRepoModel>> call, Response<List<GitRepoModel>> response) {
            int code = response.code();
            if (code == 200) {
                for(int i=0;i< response.body().size();i++){
            } else {
        public void onFailure(Call<List<GitRepoModel>> call, Throwable t) {

    a. We are creating a JSON builder first
    b. One Retrofit.builder instance is created with the api endpoint url and adding converter factory as JSON
    c. “Call” object is created from the APIService interface and one HTTP request is made to the remote webserver using enqueue method
    d. We will get the response callback on onResponse method and failure on onFailure method.

  4. Run the project and Check your logs .You will see something as below :

All the repository names are extracted from the json response.
You can see that API EndPoint is “” and url inside @GET is @GET(“users/{user}/repos”) which makes a combined url{user}/repos

  So, always remember to end your ENDPOINT Url with “/” and never begin your url inside APIService class with “/” . “call.enqueue(this)” is used to make an asynchronous call. For synchronous, you can use “execute” method. ( but use execute only on background thread)

This project is shared on GitHub


Android – DayNight View Tutorial

What is day night theme and how to use it on android application ?

Support Library 23.2 has introduced a new DayNight theme for Android Apps using which will automatically change the application theme to day or night mode based on the time of day and user’s last known location. Also, this theme can be used back up to Android Ice Cream Sandwich devices. 

android daynightview


Types of Day Night theme :
We can use any one of the following themes on our project :


Separate resources for night mode and day mode :
Sometimes we need to use different resources for different mode . This can be accomplished by using different drawable and different values folders.

a) Folder names for default mode :
b) Folder names for night mode :


In this tutorial, we will use two different drawable folders with two different images having same name. If night mode is enabled in the application, image from drawable-night will be picked up.

Similarly for showing different text colors on different mode , we will use different values folder.
  1. Create one sample project on Android Studio with an Activity as MainActivity
  2. Also, create one more Activity as DayNightActivity . We will add 3 Buttons on this Activity. Clicking on these buttons will Start DayNightActivity with different theme mode. MainActivity and DayNightActivity will look like as below :

    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
        private Button dayButton;
        private Button nightButton;
        private Button autoButton;
        protected void onCreate(Bundle savedInstanceState) {
            dayButton = (Button)findViewById(;
            nightButton = (Button)findViewById(;
            autoButton = (Button)findViewById(;
        public void onClick(View view) {
            switch (view.getId()) {
                    //change theme to auto mode
                    //Change theme to day mode
                    //change theme to night mode
            Intent intent = new Intent(MainActivity.this, DayNightActivity.class);


    package com.codevscolor.daynightview;
    import android.os.Bundle;
    public class DayNightActivity extends AppCompatActivity {
        protected void onCreate(Bundle savedInstanceState) {
            TextView title = (TextView) findViewById(;
            int themeMode = AppCompatDelegate.getDefaultNightMode();
            if (themeMode == AppCompatDelegate.MODE_NIGHT_AUTO) {
                title.setText("Current Theme : Auto");
            } else if (themeMode == AppCompatDelegate.MODE_NIGHT_NO) {
                title.setText("Current Theme : Day");
            } else if (themeMode == AppCompatDelegate.MODE_NIGHT_YES) {
                title.setText("Current Theme : Night");

     3.Update your Application’s theme inside style.xml as below :

        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="android:textColorPrimary">@color/textColorPrimary</item>

    4. Create two “values” folders : values and values-night . And update colors.xml file on each of these folders:


    <?xml version="1.0" encoding="utf-8"?>
        <color name="colorPrimary">#afb53f</color>
        <color name="colorPrimaryDark">#5b520f</color>
        <color name="colorAccent">#FF4081</color>
        <color name="textColorPrimary">#000000</color>
        <color name="colorBackground">#FFFFFF</color>


    <?xml version="1.0" encoding="utf-8"?>
        <color name="colorPrimary">#3F51B5</color>
        <color name="colorPrimaryDark">#303F9F</color>
        <color name="colorAccent">#FF4081</color>
        <color name="textColorPrimary">#FFFFFF</color>
        <color name="colorBackground">#000000</color>

     If night mode is enabled, the application will use resources from valuesnight folder and if day mode is enabled, it will use from values folder.

          5. Similarly, create two different drawable folders and place two images with same name inside both of these folders.

That’s it. You can see that if Button auto is to enable auto mode, button day is to enable day mode and night is to enable night mode in the application. You can download this application from here , and if you have any doubt, please let me know 🙂

images credit : link1, link2