Fetch and show data from API Using Volley – Example

Hi folks, today we are going to look at Volley Networking library. there are other libraries as well which used for Android networking but volley is the simplest. In this tutorial, we will fetch the data from API and show that data in Recyclerview.

https://github.com/happysingh23828/Volley-Tutorial-Androchef

The API will give a response as JSON. Here is the link you can check it out.

http://androchef.com/wp-content/uploads/2019/03/world-population-androchef.txt

In this API we are getting a list of countries with their rank, flag, population etc.

Steps to use Volley Library

  • Add Libraries to gradle

    implementation 'com.google.code.gson:gson:2.8.5' //for mapping Java objects to JSON
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.squareup.picasso:picasso:2.71828' // for showing images in RecyclerView
  • Now make a POJO class to store your one JSON object

Worldpopulation.java

import com.google.gson.annotations.SerializedName;

public class Worldpopulation {

    @SerializedName("country")
    private String mCountry;
    @SerializedName("flag")
    private String mFlag;
    @SerializedName("population")
    private String mPopulation;
    @SerializedName("rank")
    private Long mRank;

    public String getCountry() {
        return mCountry;
    }

    public void setCountry(String country) {
        mCountry = country;
    }

    public String getFlag() {
        return mFlag;
    }

    public void setFlag(String flag) {
        mFlag = flag;
    }

    public String getPopulation() {
        return mPopulation;
    }

    public void setPopulation(String population) {
        mPopulation = population;
    }

    public Long getRank() {
        return mRank;
    }

    public void setRank(Long rank) {
        mRank = rank;
    }

}
  • So as I told you we are going to show data in recyclerView .

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".normalvolleycall.MainActivity">

    <Button
        android:id="@+id/btn_load_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/load_list_using_volley"
        android:layout_gravity="center"
        android:gravity="center"
        android:background="@color/colorPrimary"
        android:layout_margin="10dp"
        android:textColor="@android:color/white" />

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:layout_gravity="center"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/flag_list_recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_margin="5dp">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>
  • We need a custom layout for each recyclerview Item

single_world_population_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/single_item_linearlayout">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_margin="10dp"
        android:elevation="100dp"
        android:translationZ="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="6">

            <ImageView
                android:id="@+id/img_flag"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_gravity="center"
                android:padding="10dp"
                android:src="@drawable/ic_launcher_background"
                android:layout_weight="1"/>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:orientation="vertical"
                android:layout_weight="3"
                android:layout_gravity="center"
                >

                <TextView
                    android:id="@+id/txt_rank"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Rank 1"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textStyle="bold"
                    android:textSize="20sp"/>

                <TextView
                    android:id="@+id/txt_country_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Country Name"
                    android:gravity="center"
                    android:textStyle="bold"

                    />

                <TextView
                    android:id="@+id/txt_population"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Population"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textStyle="bold"
                    />
                
            </LinearLayout>

        </LinearLayout>
        
    </android.support.v7.widget.CardView>
    
</LinearLayout>
  • We also need a custom adaptor for recyclerView

CustomRecyclerAdapter.java

package com.androchef.volley.normalvolleycall;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.androchef.volley.R;
import com.squareup.picasso.Picasso;

import java.util.List;

public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.CustomRecyclerViewHolder> {

    private List<Worldpopulation> listOfPopulation;
    private Context context;

    public CustomRecyclerAdapter(List<Worldpopulation> listOfPopulation, Context context) {
            this.listOfPopulation = listOfPopulation;
            this.context = context;
    }

    @NonNull
    @Override
    public CustomRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new CustomRecyclerViewHolder(LayoutInflater.from(context).inflate(R.layout.single_world_population_item,viewGroup,false));
    }

    @Override
    public void onBindViewHolder(@NonNull CustomRecyclerViewHolder customRecyclerViewHolder, int i) {
        customRecyclerViewHolder.bind(listOfPopulation.get(i));
    }

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

    class CustomRecyclerViewHolder extends RecyclerView.ViewHolder{

        View view;
        TextView countryName,countryPopulationCount,countryRank;
        ImageView countryFlag;

        CustomRecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
            this.view = itemView;
            countryFlag = view.findViewById(R.id.img_flag);
            countryName = view.findViewById(R.id.txt_country_name);
            countryRank = view.findViewById(R.id.txt_rank);
            countryPopulationCount = view.findViewById(R.id.txt_population);
        }

        void bind(Worldpopulation worldpopulation){
            countryName.setText(worldpopulation.getCountry());
            countryPopulationCount.setText(worldpopulation.getPopulation());
            countryRank.setText(String.valueOf(worldpopulation.getRank()));
            Picasso.get().load(worldpopulation.getFlag()).into(countryFlag);
        }
    }
}
  • Now fetching and showing data using volley library

MainActivity.java

package com.androchef.volley.normalvolleycall;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.androchef.volley.R;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Button btnLoadList;
    ProgressBar progressBar;
    RecyclerView recyclerView;
    CustomRecyclerAdapter adapter;
    List<Worldpopulation> listOfWorldPopulations = new ArrayList<>();

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

    private void init() {
        btnLoadList = findViewById(R.id.btn_load_list);
        progressBar = findViewById(R.id.progress_bar);
        recyclerView = findViewById(R.id.flag_list_recyclerView);
        adapter = new CustomRecyclerAdapter(listOfWorldPopulations, this);
    }


    private void setRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }


    private void onClicks() {
        btnLoadList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadWorldPopulationListFromVolley();
            }
        });
    }

    private void loadWorldPopulationListFromVolley() {
        //Showing Progress while fetching data from server
        progressBar.setVisibility(View.VISIBLE);

        //Our End point from where we will get our json data
        String url = "http://androchef.com/wp-content/uploads/2019/03/world-population-androchef.txt";

        //We will get response as string and we will convert it into List<WorldPopulation> object
        StringRequest fetchWorldPopulationRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                //converting json string response to List of WorldPopulation objects :-)
                List<Worldpopulation> worldpopulationList = new Gson().fromJson(response, new TypeToken<List<Worldpopulation>>(){}.getType());

                //updating or notifying adapter to show latest fetched list
                listOfWorldPopulations.clear();
                listOfWorldPopulations.addAll(worldpopulationList);
                adapter.notifyDataSetChanged();

                //hide progress bar
                progressBar.setVisibility(View.GONE);
            }

            }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {


                //hide progress bar
                progressBar.setVisibility(View.GONE);

                //when we got some network error while fetching data
                Toast.makeText( MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
            }

        });

        //Creating a new request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //adding this fetchWorldPopulationRequest to in queue and executing it.
        requestQueue.add(fetchWorldPopulationRequest);
    }
}

Congrats, You have successfully fetched data from API using Volley Library. If you find any difficulty while implementing this please let me know in the comment section I will happy to help you. or if you have any suggestions or feedback then your most welcome.

Github Link

https://github.com/happysingh23828/Volley-Tutorial-Androchef

See you in next post Bye Bye 🙂

If you are a beginner and wants to learn Android Development Here is My Roadmap.

Others Tutorials Links