Fetch data in Recyclerview using volley library in Android: Complete project

Most of you don’t know how to fetch data from the server in Android Recyclerview. So In this article, we will develop a complete project in which we fetch the data using the Volley library. So read the full post completely

In order to get data from the server, we need

  • A Restful Web API.
  • Volley library to fetch data from API

Here we will not create any API, In place of this, we use Artificial API of JSONplaceholder. This API fetches the post from the server. The URL of API is:

https://jsonplaceholder.typicode.com/posts

If you hit this URL in the browser, you will get a Json response of 100 posts like this.

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
  },
  {
    "userId": 1,
    "id": 5,
    "title": "nesciunt quas odio",
    "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
  }
]

Hope so you are interested to know how to fetch data in recycler view using volley in Android, so now without wasting much time let’s start.

You can also refer our video tutorial for same.

 

Fetch data in Recyclerview using volley library in Android

1. Create a new project in Android Studio by navigating to File ⇒ New ⇒ New Project and provide a name to your project. choose Empty activity. By default activity name is MainActivity.java.

2. Here we need Recyclerview and volley library in our project, so first add the dependency of Volley library and Recyclerview in your build.gradle file in the Android project. and also add the dependency of card view in order to make the UI more attractive.

dependencies {
     // recyclerview dependency
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    //cardview dependency
    implementation 'androidx.cardview:cardview:1.0.0'
    // volley dependency
    implementation 'com.android.volley:volley:1.1.1'
}

3. Now open menifest.xml file and add the Internet Permission in your manifiest file

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

4. Now go to the activity_main.xml  file and create the recyclerview.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"/>
</RelativeLayout>

Design Row layout xml file of Recyclerview

5. Now create a new layout res file by navigating res => layout=> New => Layout resource file =>rowitem.xml and put the below line of codes to make the row design for recycleview.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/card"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linear"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/userId"
                android:text="1"
                android:textSize="20dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="20dp"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/postTitle"
                android:text="Title"
                android:textSize="20dp"
                android:fontFamily="sans-serif-medium"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="20dp"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/postDesc"
                android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"
                android:textSize="15dp"
                android:layout_marginBottom="20dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="20dp"/>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>

Create Model(POJO) and Adapter class

6. Now create a new java class and give it the name as PostModel.java and paste the below lines of code. This class is known as the POJO class.

package com.thecodingshef.volleyrecycler;
public class PostModel {
    int userId;
    String Title,PostDesc;
    public PostModel(int userId, String title, String postDesc) {
        this.userId = userId;
        Title = title;
        PostDesc = postDesc;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getTitle() {
        return Title;
    }
    public void setTitle(String title) {
        Title = title;
    }
    public String getPostDesc() {
        return PostDesc;
    }
    public void setPostDesc(String postDesc) {
        PostDesc = postDesc;
    }
}

7. Now open MainActivity.java file and paste the below lines of code to implement RecyclerView.

package com.thecodingshef.volleyrecycler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.List;
public  class MainActivity extends AppCompatActivity {
    List<PostModel> postList=new ArrayList<>();
    RecyclerView recyclerView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);   
    }
}

8. Now let’s create the adapter class for our Recyclerview, in order to bind the data in recycler view. Give it name PostAdapter.java. and write the following code.

package com.thecodingshef.volleyrecycler;
import android.app.DownloadManager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    List<PostModel> postList;
    public PostAdapter(Context context, List<PostModel> postList) {
        this.postList=postList;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem,parent,false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    }
    @Override
    public int getItemCount() {
        return postList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView title,postdesc,userId;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title=itemView.findViewById(R.id.postTitle);
            postdesc=itemView.findViewById(R.id.postDesc);
            userId=itemView.findViewById(R.id.userId);
        }
    }
}

Implement volley To fetch data

9. Now it is time to fetch data in recyclerview, Create a method of named GetData in onCreate method of MainActivity.java. In the GetData method first, create a progress dialog, then create a Requestqueue in order to add the request into queue.

Now Create the object JsonArrayObject class and get the data from the response and add the data into the PostList. Pass the PostList in the constructor of adapter class and then set the adapter in Recyclerview.

private void GetData() {
        final ProgressDialog progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                for(int i=0;i<=response.length();i++){
                    try {
                        JSONObject jsonObject =response.getJSONObject(i);
                        postList.add(new PostModel(
                                jsonObject.getInt("userId"),
                                jsonObject.getString("title"),
                                jsonObject.getString("body")
                        ));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        progressDialog.dismiss();
                    }
                }
                adapter=new PostAdapter(getApplicationContext(),postList);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonArrayRequest);
    }

10. Now go to PostAdapter class and get the data from PostList and set into the views of row item in onBindViewHolder Method

 

 @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {  holder.userId.setText(Integer.toString(postList.get(position).getUserId()));
        holder.title.setText(postList.get(position).getTitle());
        holder.postdesc.setText(postList.get(position).getPostDesc());
    }

Complete code of PostAdapter class:

package com.thecodingshef.volleyrecycler;
import android.app.DownloadManager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    List<PostModel> postList;
    public PostAdapter(Context context, List<PostModel> postList) {
        this.postList=postList;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem,parent,false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        holder.userId.setText(Integer.toString(postList.get(position).getUserId()));
        holder.title.setText(postList.get(position).getTitle());
        holder.postdesc.setText(postList.get(position).getPostDesc());
    }
    @Override
    public int getItemCount() {
        return postList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView title,postdesc,userId;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title=itemView.findViewById(R.id.postTitle);
            postdesc=itemView.findViewById(R.id.postDesc);
            userId=itemView.findViewById(R.id.userId);
        }
    }
}

Cool! Our data is fetch in recyclerview using volley.

Implement search using EditText in Recyclerview

Now we want to implement a search in recyclerview in order to filter the data using user id.

11. Open the activity_main.xml file and create an edit text before recyclerview. Your code looks like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/search"
        android:hint="search here by userid"
        android:layout_marginTop="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="20dp"/>
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:layout_below="@+id/search"/>
</RelativeLayout>

12. Now go to the MainActivity.java file and typecast the EditText and implement the addTextChangeListner on EditText.

search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                filterList.clear();
                if(s.toString().isEmpty()){
                    recyclerView.setAdapter(new PostAdapter(getApplicationContext(),postList));
                    adapter.notifyDataSetChanged();
                }
                else{
                    Filter(s.toString());
                }
            }
        });

13. Now create the Filter method outsite the onCreate method of MainActivity.java class, and copy the code from here.

private void Filter(String text) {
        for(PostModel post:postList){
            if(Integer.toString(post.getUserId()).equals(text)){
                filterList.add(post);
            }
        }
        recyclerView.setAdapter(new PostAdapter(getApplicationContext(),filterList));
        adapter.notifyDataSetChanged();
    }

Complete code of MainActivity.java class:

package com.thecodingshef.volleyrecycler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public  class MainActivity extends AppCompatActivity {
    List<PostModel> postList=new ArrayList<>();
    String url="https://jsonplaceholder.typicode.com/posts";
    PostAdapter adapter;
    List<PostModel> filterList=new ArrayList<>();
    RecyclerView recyclerView;
    EditText search;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recyclerview);
        search=findViewById(R.id.search);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                filterList.clear();
                if(s.toString().isEmpty()){
                    recyclerView.setAdapter(new PostAdapter(getApplicationContext(),postList));
                    adapter.notifyDataSetChanged();
                }
                else{
                    Filter(s.toString());
                }
            }
        });
        GetData();
    }
    private void Filter(String text) {
        for(PostModel post:postList){
            if(Integer.toString(post.getUserId()).equals(text)){
                filterList.add(post);
            }
        }
        recyclerView.setAdapter(new PostAdapter(getApplicationContext(),filterList));
        adapter.notifyDataSetChanged();
    }
    private void GetData() {
        final ProgressDialog progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                for(int i=0;i<=response.length();i++){
                    try {
                        JSONObject jsonObject =response.getJSONObject(i);
                        postList.add(new PostModel(
                                jsonObject.getInt("userId"),
                                jsonObject.getString("title"),
                                jsonObject.getString("body")
                        ));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        progressDialog.dismiss();
                    }
                }
                adapter=new PostAdapter(getApplicationContext(),postList);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonArrayRequest);
    }
}

Now the code is complete, so run your application.

If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

Thank you 🙂 Keep Learning !

Leave a Comment

Your email address will not be published. Required fields are marked *