Feeling Restful? Well gas up! Because we are about to Launch. This project is a very simple Android Project aimed at getting you to implement some simple concepts that are very important as far as Android Development is concerned.
In this project, you are going to implement a mobile design of the GADS 2020 Leaderboard.

The mobile App will display Top 20 learners in the Learning Leaders’ category and Top 20 learners in the Skill IQ Leaders’ category. We are going to Fetch Data From an API(Application Programming Interface) which is Hosted on Heroku and Display Data on The Mobile App, sounds interesting? We just getting started. This project is for beginners , intermediate and senior developers who would want to get their hands dirty on  Restful APIs on Android

https://gadsapi.herokuapp.com/    you can get the hosted API here as well as the endpoints we are going to use.

This Project will make you understand

  1. Multi-Activity
  2. View pager
  3. Customizing Toolbar
  4. RecyclerView
  5. Adapters
  6. Making Network Request using Retrofit to an endpoint through a @GET request

what it looks like sending requests through a mobile client and getting response from the api web serviceappwebservice

PREREQUISITES

  1. Some Basics on Android mobile development
  2. Basic fundamentals on Java Programming Language
  3. Basic Design Concepts


Photo by Windows / Unsplash

What you need to get started

  1. install android studio
  • you are set to go!
Download Android Studio and SDK tools | Android Developers
<!-- hide description -->

LETS GET YOU STARTED....

  1. First open android studio and create a new project
    First start a new Android Project by going to File > New project or just tap the Create New Project button on the start page of your Android Studio.
  2. newandroidstudiophoto
    Choose Empty Activity as your project template, then click next.
    creatproject
    Give any name to your project, in my case i named it LeaderBoard for this project and then click finish and wait until the project build successfuly.

  1. Now add the following dependencies on the build.gradle(Module :app)dependencyphoto

//added retrofit dependencies
implementation("com.squareup.moshi:moshi:1.9.3")
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
//gson library
implementation 'com.google.code.gson:gson:2.8.6'
//Glide library
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

// Retrofit and GSON
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'


// Logging
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

//An okHttp interceptor which logs HTTP requests and data response

implementation 'com.squareup.okhttp3:okhttp:3.14.9'

** Now when you are done sync the project and wait for build to finish successfully**

This is How Your Manifest File Should Look Like remmeber to add internet permission
manifest


Lets Get the Layouts done

  1. learning_leaders_fragmet Layout xml file
    learningleaderslayout

  2. skill_iq_fragmet Layout xml file
    skilliqlayout

LETS GET HANDS-ON....

Create a new Java class and name it viewpageradapter this class will assist us is scrolling between two tabs which are skill_iq tab and learning_leaders tab
the class extends FragmentPagerAdapterviewpager

here is a snippet code....

public class viewpageradapter extends FragmentPagerAdapter {
public viewpageradapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}

public viewpageradapter(FragmentManager supportFragmentManager) {
    super(supportFragmentManager);
}

@NonNull
@Override
public Fragment getItem(int position) {
    switch (position){
        case 0:
            return new learning_leaders();
        case 1:
            return new Skill_iq();
        default:
            return null;
    }

}

@Override
public int getCount() {
    return 2;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {

    switch (position) {
        case 0:
            return "Learning Leaders";
        case 1:
            return "Skill IQ Leaders";
    } return super.getPageTitle(position);
}

}

Next lets create a new Package under Java Folder and name it Model then inside Model lets create two Java Classes

1 LeaderBoard java class
leaderboard-1
here is a snippet code...
NB make sure you use Serialize

public class LeaderBoard {
@SerializedName("name")
@Expose
private String name;
@SerializedName("hours")
@Expose
private String hours;
@SerializedName("badgeUrl")
@Expose
private String image;
@SerializedName("country")
@Expose
private String country;

//add this constructor
public LeaderBoard() {

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getHours() {
    return hours;
}

public void setHours(String hours) {
    this.hours = hours;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getCountry() { return country;}

public void setCountry(String country) {this.country = country;}

@Override
public String toString() {
    return "LeaderBoard{" +
            "name='" + name + '\'' +
            ", hours='" + hours + '\'' +
            ", image=" + image +


            '}';
}

}

2.SkillIQ Java Class
skilliq

here is the code snippet...

public class SkillIQ {
@SerializedName("name")
@Expose
private String name;
@SerializedName("skilliq")
@Expose
private String skilliq;
@SerializedName("badgeUrl")
@Expose
private String image;
@SerializedName("country")
@Expose
private String country;

public SkillIQ() {

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSkilliq() {
    return skilliq;
}

public void setSkilliq(String skilliq) {
    this.skilliq = skilliq;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

@Override
public String toString() {
    return "SkillIQ{" +
            "name='" + name + '\'' +
            ", skilliq='" + skilliq + '\'' +
            ", image='" + image + '\'' +
            ", country='" + country + '\'' +
            '}';
}

}

Now we are going to make two fragments by creating the corresponding Java classes which will extend Fragment

  1. learning_leaders fragment
  2. skill_iq fragment

1.Learning leaders frament which extends Frament
learniningleadersfragment
here is a code snippet...

public class learning_leaders extends Fragment {

private RecyclerView recyclerView;
private LearningLeadersAdapter learningLeadersAdapter;
private List<LeaderBoard> leaderBoard;


//add a public constructor
public learning_leaders() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View view = inflater.inflate(R.layout.fragment_learning_leaders, container, false);
    recyclerView = view.findViewById(R.id.learning_leaders);
    leaderBoard = new ArrayList<>();
    return view;

}

2.skill_iq fragmentskill_iqfragment

code snippet...

public class Skill_iq extends Fragment {

//add a public constructor
public Skill_iq() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View view = inflater.inflate(R.layout.fragment_skill_iq, container, false);
   
    return view;
}

Great we are almost done hold on for a while!!!

Next Step is making adapters package and creating the two adapters

  1. SkillIQ adapter
    skilliqadapter

code snippet...

public class SkillIQAdapter extends RecyclerView.Adapter<SkillIQAdapter.ViewHolder> {
//initialize the array list
private List skillIQ = new ArrayList<>();

//initialize the constructor
public SkillIQAdapter() {

}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.skill_iq_item, parent, false);
    return new SkillIQAdapter.ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.bind(skillIQ.get(position));
}

@Override
public int getItemCount() {
    return skillIQ.size();
}

public void setSkillIQ(List<SkillIQ> skillIQ) {
    this.skillIQ = skillIQ;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    //initialize views on skill_iq_item
    private TextView textView1, textView2, country;
    private ImageView image;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        textView1 = itemView.findViewById(R.id.skill_textView_1);
        textView2 = itemView.findViewById(R.id.skill_textView_2);
        country = itemView.findViewById(R.id.country2);
        image = itemView.findViewById(R.id.skill_image);

    }

    public void bind(SkillIQ skillIQ) {
        textView1.setText(skillIQ.getName());
        textView2.setText(skillIQ.getSkilliq());
        country.setText(skillIQ.getCountry());
      //use glide to load the image
        Glide.with(image.getContext())
                .load(skillIQ.getImage())
                .centerCrop()
                .into(image);
    }

}

}

2.LearningLeadersAdapter
learniningleadersfragment-1
code snippet...

public class SkillIQAdapter extends RecyclerView.Adapter<SkillIQAdapter.ViewHolder> {
//initialize the array list
private List skillIQ = new ArrayList<>();

//initialize the constructor
public SkillIQAdapter() {

}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.skill_iq_item, parent, false);
    return new SkillIQAdapter.ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.bind(skillIQ.get(position));
}

@Override
public int getItemCount() {
    return skillIQ.size();
}

public void setSkillIQ(List<SkillIQ> skillIQ) {
    this.skillIQ = skillIQ;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    //initialize views on skill_iq_item
    private TextView textView1, textView2, country;
    private ImageView image;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        textView1 = itemView.findViewById(R.id.skill_textView_1);
        textView2 = itemView.findViewById(R.id.skill_textView_2);
        country = itemView.findViewById(R.id.country2);
        image = itemView.findViewById(R.id.skill_image);

    }

    public void bind(SkillIQ skillIQ) {
        textView1.setText(skillIQ.getName());
        textView2.setText(skillIQ.getSkilliq());
        country.setText(skillIQ.getCountry());

        Glide.with(image.getContext())
                .load(skillIQ.getImage())
                .centerCrop()
                .into(image);
    }

}

}

Lets create Service package and inside the package lets create..

  1. ServiceBuilder Class
  2. SkillDataService java interface
  3. LearningLeaderService java interface

1.ServiceBuilder Class
buliderservice

code snippet...

public class ServiceBuilder {

    private static final String URL = "https://gadsapi.herokuapp.com/";
    private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(URL)
            .addConverterFactory(GsonConverterFactory.create());

    // Create logger
    private static HttpLoggingInterceptor logger =
            new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);

    // Create OkHttp Client
    private static OkHttpClient.Builder okHttp =
            new OkHttpClient.Builder().addInterceptor(logger);

    private static Retrofit retrofit = builder.build();

    //helper class to assist in building services
    public static <S> S buildService(Class<S> serviceType) {
            return retrofit.create(serviceType);
    }

    private final static String SEND_URL = "https://docs.google.com/forms/d/e/";
    private static Retrofit.Builder build = new Retrofit.Builder().baseUrl(SEND_URL)
            .addConverterFactory(GsonConverterFactory.create());
    

    public <P> P buildServices(Class<P> endpoint) {
            return retrofit.create(endpoint);
    }

}

2.SkillIQDataService java interface
skilliqinterface

code snippet....

public interface SkillIQDataService {

//pass the base Url here
String baseUrl = "https://gadsapi.herokuapp.com";

//get request to get the data from the base Url and display on the app
@GET("/api/skilliq")
Call<List> skillIQService();
}

3.LeaderBoardDataService
leaderboarddataservice

code snippet...

public interface LeaderBoardDataService {

String baseUrl = "https://gadsapi.herokuapp.com";

@GET("/api/hours")
Call<List<LeaderBoard>> learningLeaders();

}

Finally here is where the Magic happens

We are going to make a request inside the respective learning_leaders fragment and skill_iq fragment and set the adapters as well as the Recyclerview. Inside OnViewCreated we are going to retrive data from the base URL and display the data

1.First lets make the request on learning_leaders fragment inside OnViewCreated
requestlearningleaders

code snippet...
NB make sure you initialize the RecyclerView , LearningLeadersAdapter and the List as follows inside the learning_leaders fragment
and add a constructor

//initialize them here
private RecyclerView recyclerView;
private LearningLeadersAdapter learningLeadersAdapter;
private List leaderBoard;

//add a public constructor
public learning_leaders() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_learning_leaders, container, false);
recyclerView = view.findViewById(R.id.learning_leaders);
leaderBoard = new ArrayList<>();
return view;

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    LeaderBoardDataService leaderBoardDataService = ServiceBuilder.buildService(LeaderBoardDataService.class);
    Call<List<LeaderBoard>> leaderBoardRequest = leaderBoardDataService.learningLeaders();

    leaderBoardRequest.enqueue(new Callback<List<LeaderBoard>>() {
        @Override
        public void onResponse(Call<List<LeaderBoard>> call, Response<List<LeaderBoard>> response) {
            learningLeadersAdapter = new LearningLeadersAdapter();
            learningLeadersAdapter.setLeaderBoard(response.body());
            recyclerView.setAdapter(learningLeadersAdapter);
        }

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

        }
    });

}

}

here is the data that will be displayed
leaderboardFinalPicture

2.Second and final step lets repeat the same process for Skill_iq fragmentrequestskilliq

code snippet...

//initialize the RecView , Adapter and the List
private RecyclerView recyclerView;
private SkillIQAdapter skillIQAdapter;
private List<Skill_iq> skillIq;

//add a public constructor
public Skill_iq() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_skill_iq, container, false);
recyclerView = view.findViewById(R.id.skill_iq);
skillIq = new ArrayList<>();
return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    SkillIQDataService skillIQDataService = ServiceBuilder.buildService(SkillIQDataService.class);
    Call<List<SkillIQ>> skillIQRequest = skillIQDataService.skillIQService();

    skillIQRequest.enqueue(new Callback<List<SkillIQ>>() {
        @Override
        public void onResponse(Call<List<SkillIQ>> call, Response<List<SkillIQ>> response) {
            skillIQAdapter = new SkillIQAdapter();
            skillIQAdapter.setSkillIQ(response.body());
            recyclerView.setAdapter(skillIQAdapter);
        }

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

        }
    });

here is what will be displayed
skillIQfinalPicture

skyswyp/GADS-Leaderboard_2
Contribute to skyswyp/GADS-Leaderboard_2 development by creating an account on GitHub.
You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.