How to Build an Instagram Like Custom RecyclerView in Android?

28 Nov, 2021
We have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Instagram like Custom RecyclerView in Android. 
We will be building a simple application in which we will be displaying data from the Instagram profile, and we will be using an official Instagram API to load the data from user’s Instagram profile and display that data in a custom RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file  
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.    
// dependency for loading data from json file.
implementation ‘com.android.volley:volley:1.1.1’
// dependency for loading image from url.
implementation ‘com.squareup.picasso:picasso:2.71828’
// dependency for creating a circle image.  
implementation ‘de.hdodenhof:circleimageview:3.1.0’
Step 3: Creating API for getting the data for generating API 
Now for creating a basic display API for Instagram posts we will be creating an API for displaying this data. You may refer to the How to Generate API URL for Public Instagram Feeds in Android? Now we have created the URL with the access token and we will use this URL to get the JSON data.  
Step 4: Adding permissions for the internet in the AndroidManifest.xml file
As we are loading data from the internet. For that, we will have to add the internet permissions to our AndroidManifest.xml file. Navigate to the app > AndroidManifest.xml file and add the below code to it. 
XML
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">          <!--recycler view for displaying        our Instagram posts-->    <androidx.recyclerview.widget.RecyclerView        android:id="@+id/idRVInstaFeeds"        android:layout_width="match_parent"        android:layout_height="match_parent" />      <!--progressbar for displaying         our loading indicator-->    <ProgressBar        android:id="@+id/idLoadingPB"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:visibility="visible" />  </RelativeLayout>
Step 6: Creating a new layout file for displaying each item of our RecyclerView 
Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as insta_feed_rv_item and add the below code to it. 
XML
<?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">      <LinearLayout        android:id="@+id/idLLTopBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:padding="4dp">                  <!--circle image for displaying the user image-->        <de.hdodenhof.circleimageview.CircleImageView            android:id="@+id/idCVAuthor"            android:layout_width="40dp"            android:layout_height="40dp"            android:layout_margin="5dp" />          <!--text view for displaying user name-->        <TextView            android:id="@+id/idTVAuthorName"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_margin="3dp"            android:padding="3dp"            android:text="geeks_for_geeks"            android:textColor="@color/black"            android:textStyle="bold" />    </LinearLayout>      <!--image view to display the post image-->    <ImageView        android:id="@+id/idIVPost"        android:layout_width="match_parent"        android:layout_height="300dp"        android:layout_below="@id/idLLTopBar"        android:adjustViewBounds="true"        android:scaleType="centerCrop" />      <!--text view to display likes count-->    <TextView        android:id="@+id/idTVLikes"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idIVPost"        android:layout_margin="6dp"        android:padding="5dp"        android:text="likes"        android:textColor="@color/black"        android:textStyle="bold" />      <!--text view to display the caption        in instagram post-->    <TextView        android:id="@+id/idTVPostDesc"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTVLikes"        android:layout_margin="6dp"        android:padding="5dp"        android:textColor="@color/black"        android:textSize="11sp" />      </RelativeLayout>
Step 7: Create a Modal Class to store data for our Feed
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as InstaModal. 
Java
public class InstaModal {    // variables for storing data     // of our recycler view item    private String id;    private String media_type;    private String permalink;    private String media_url;    private String username;    private String caption;    private String timestamp;      public String getAuthor_url() {        return author_url;    }      public void setAuthor_url(String author_url) {        this.author_url = author_url;    }      public int getLikesCount() {        return likesCount;    }      public void setLikesCount(int likesCount) {        this.likesCount = likesCount;    }      private String author_url;    private int likesCount;      public String getId() {        return id;    }      public void setId(String id) {        this.id = id;    }      public String getMedia_type() {        return media_type;    }      public void setMedia_type(String media_type) {        this.media_type = media_type;    }      public String getPermalink() {        return permalink;    }      public void setPermalink(String permalink) {        this.permalink = permalink;    }      public String getMedia_url() {        return media_url;    }      public void setMedia_url(String media_url) {        this.media_url = media_url;    }      public String getUsername() {        return username;    }      public void setUsername(String username) {        this.username = username;    }      public String getCaption() {        return caption;    }      public void setCaption(String caption) {        this.caption = caption;    }      public String getTimestamp() {        return timestamp;    }      public void setTimestamp(String timestamp) {        this.timestamp = timestamp;    }      public InstaModal(String id, String media_type, String permalink, String media_url, String username,                      String caption, String timestamp, String author_url, int likesCount) {        this.id = id;        this.media_type = media_type;        this.permalink = permalink;        this.media_url = media_url;        this.username = username;        this.caption = caption;        this.timestamp = timestamp;        this.author_url = author_url;        this.likesCount = likesCount;    }}
Step 8: Creating an Adapter class for setting this data to each item of our RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name it as InstagramFeedRVAdapter and add the below code to it. 
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;  import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;  import com.squareup.picasso.Picasso;  import java.util.ArrayList;  import de.hdodenhof.circleimageview.CircleImageView;  public class InstagramFeedRVAdapter extends RecyclerView.Adapter<InstagramFeedRVAdapter.ViewHolder> {      private ArrayList<InstaModal> instaModalArrayList;    private Context context;      public InstagramFeedRVAdapter(ArrayList<InstaModal> instaModalArrayList, Context context) {        this.instaModalArrayList = instaModalArrayList;        this.context = context;    }      @NonNull    @Override    public InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        // inflating our layout for item of recycler view item.        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false);        return new InstagramFeedRVAdapter.ViewHolder(view);    }      @Override    public void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) {        InstaModal modal = instaModalArrayList.get(position);        holder.authorTV.setText(modal.getUsername());        if (modal.getMedia_type().equals("IMAGE")) {            Picasso.get().load(modal.getMedia_url()).into(holder.postIV);        }        holder.desctv.setText(modal.getCaption());        holder.likeTV.setText("" + modal.getLikesCount() + " likes");        Picasso.get().load(modal.getAuthor_url()).into(holder.authorIV);    }      @Override    public int getItemCount() {        return instaModalArrayList.size();    }      public class ViewHolder extends RecyclerView.ViewHolder {          CircleImageView authorIV;        private TextView authorTV;        private ImageView postIV;        private TextView likeTV, desctv;          public ViewHolder(@NonNull View itemView) {            super(itemView);            authorIV = itemView.findViewById(R.id.idCVAuthor);            authorTV = itemView.findViewById(R.id.idTVAuthorName);            postIV = itemView.findViewById(R.id.idIVPost);            likeTV = itemView.findViewById(R.id.idTVLikes);            desctv = itemView.findViewById(R.id.idTVPostDesc);        }    }}
Step 9: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast;  import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;  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.JsonObjectRequest;import com.android.volley.toolbox.Volley;  import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;  import java.util.ArrayList;  public class MainActivity extends AppCompatActivity {      // creating variables for our requestqueue,     // array list, progressbar, edittext,     // image button and our recycler view.    private RequestQueue mRequestQueue;    private ArrayList<InstaModal> instaModalArrayList;    private ProgressBar progressBar;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                  // initializing our views.        progressBar = findViewById(R.id.idLoadingPB);        instaModalArrayList = new ArrayList<>();                  // calling method to load        // data in recycler view.        getInstagramData();    }      private void getInstagramData() {        // below line is use to initialize the variable for our request queue.        mRequestQueue = Volley.newRequestQueue(MainActivity.this);          // below line is use to clear cache this will        // be use when our data is being updated.        mRequestQueue.getCache().clear();                  // below is the url for getting data         // from API in json format.        String url = "Enter your URL";                 // below line we are  creating a new request queue.        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {            @Override            public void onResponse(JSONObject response) {                progressBar.setVisibility(View.GONE);                try {                    JSONArray dataArray = response.getJSONArray("data");                    for (int i = 0; i < dataArray.length(); i++) {                        // below line is to extract data from JSON file.                        JSONObject dataObj = dataArray.getJSONObject(i);                        String id = dataObj.getString("id");                        String media_type = dataObj.getString("media_type");                        String permalink = dataObj.getString("permalink");                        String media_url = dataObj.getString("media_url");                        String username = dataObj.getString("username");                        String caption = dataObj.getString("caption");                        String timestamp = dataObj.getString("timestamp");                                                 // below line is to add a constant author image URL to our recycler view.                        String author_url = "https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B";                        int likesCount = 100 + (i * 10);                                                  // below line is use to add data to our modal class.                        InstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount);                                                  // below line is use to add modal                         // class to our array list.                        instaModalArrayList.add(instaModal);                                                  // below line we are creating an adapter class and adding our array list in it.                        InstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this);                        RecyclerView instRV = findViewById(R.id.idRVInstaFeeds);                                                 // below line is for setting linear layout manager to our recycler view.                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);                                                 // below line is to set layout manager to our recycler view.                        instRV.setLayoutManager(linearLayoutManager);                                                  // below line is to set adapter                         // to our recycler view.                        instRV.setAdapter(adapter);                    }                } catch (JSONException e) {                    // handling error case.                    e.printStackTrace();                    Toast.makeText(MainActivity.this, "Fail to get Data.." + e.getMessage(), Toast.LENGTH_SHORT).show();                }            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {                // handling error message.                Toast.makeText(MainActivity.this, "Fail to get Data.." + error, Toast.LENGTH_SHORT).show();            }        });        queue.add(jsonObjectRequest);    }}
Now run your app and see the output of the app. 
Check out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp/tree/InstagramCustomListVIew
kalrap615
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.