TrinityTuts

Working with RecyclerView in Android Application

Last updated on August 28th, 2020 at 05:14 pm

In this tutorial, I am going to explain how we can create and use RecyclerView in our Android Application in simple steps. RecyclerView is an advance version of ListView.

https://github.com/anehkumar/RecyclerViewAndroidTutorial/

 

Step 1. Create a new Android project and name It in my case my project name is RecyclerGridView.

Step 2. Now before we start we need to add some dependencies in our app so open app -> build.gradle and add below code in it

dependencies {
    /..../

    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation("com.squareup.okhttp3:okhttp:4.0.0")
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}

Step 3. Now open AndroidManifest.xml and add Internet permission to make a network calls to load data.


Step 4. Now create two packages inside your main package as shown in the image below

Adapter and model are two folders which I create, model folder holds data which we load from API and in adapter folder, we can create Adapter which set data in View

Step 5. Now we can create a Model my model name is ImageModel and paste below code in it

package com.recyclergridview.model;

public class ImageModel {
    int id;
    String url;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPhotographer() {
        return photographer;
    }

    public void setPhotographer(String photographer) {
        this.photographer = photographer;
    }

    String photographer;
}

Step 6. Now create ImagesAdapter file inside the adapter folder and paste below code in it.

package com.recyclergridview.adapter;

import android.app.Activity;
import android.content.Context;
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.bumptech.glide.Glide;
import com.recyclergridview.R;
import com.recyclergridview.model.ImageModel;

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


public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.CustomViewHolder> {

    private List<ImageModel> imageModelsList;
    private Context mContext;
    private Activity act;

    public ImagesAdapter(Context context, ArrayList<ImageModel> imageList, Activity activity) {
        this.imageModelsList = imageList;
        this.mContext = context;
        this.act = activity;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.mContext).inflate(R.layout.image_item, parent, false);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CustomViewHolder holder, final int position) {
        final ImageModel get = imageModelsList.get(position);

        holder.photographer.setText(get.getPhotographer());
        final String image = get.getUrl();
        Glide
                .with(this.mContext)
                .load(image)
                .into(holder.image);

    }


    @Override
    public int getItemCount() {
        return (null != imageModelsList ? imageModelsList.size() : 0);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {

        ImageView image;
        TextView photographer;

        public CustomViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.image);
            photographer = (TextView) itemView.findViewById(R.id.photographer);

        }
    }
}

In the above code first, we extend RecyclerView Adapter and pass or customViewHolder class in it in CustomViewHolder class we basically find view by its id as shown in the above code. Now in our main class ImagesAdapter we create a constructor and pass three thing ArrayList(Data), Parent context and activity. In the above code, you also see I import some method from the adapter class.

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.mContext).inflate(R.layout.image_item, parent, false);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
}

In above code pass our View which we can Inflate in our RecyclerView and also pass that view to our CustomViewHolder where we can find view by its Id.

@Override
    public int getItemCount() {
        return (null != imageModelsList ? imageModelsList.size() : 0);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

Now above code is easy to understand by its name so there is no need for explanation. In the above code, we find position get the size of the array we pass from the constructor.

@Override
    public void onBindViewHolder(CustomViewHolder holder, final int position) {
        final ImageModel get = imageModelsList.get(position);

        holder.photographer.setText(get.getPhotographer());
        final String image = get.getUrl();
        Glide
                .with(this.mContext)
                .load(image)
                .into(holder.image);

    }

Now in the above code, we can set data to view. In my case, I set an image and text in our app.

Step 7. In this step, I am creating a Layout file which I am using in the above code in onCreateViewHolder method

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

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="250dp" />

    <TextView
        android:id="@+id/photographer"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Step 8. Now we can call all this code in our MainActivity class as shown in below code and I am also using http://pexels.com API to load the image using OkHttp if you want to learn how we can load data from API follow this post GET And POST request using OKHttp in Android Application.

package com.recyclergridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.recyclergridview.adapter.ImagesAdapter;
import com.recyclergridview.model.ImageModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    RecyclerView imageList;

    GridLayoutManager gridLayoutManager;
    ImagesAdapter imagesAdapters;
    ArrayList<ImageModel> imageModelArrays;

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

        imageList = (RecyclerView)findViewById(R.id.imageList);

        gridLayoutManager = new GridLayoutManager(getApplicationContext(),2, LinearLayoutManager.VERTICAL,false);
        imageList.setLayoutManager(gridLayoutManager);

        imageModelArrays = new ArrayList<>();

        imagesAdapters = new ImagesAdapter(MainActivity.this, imageModelArrays, this);
        imageList.setAdapter(imagesAdapters);


        try {
            getImageFromPexels();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void getImageFromPexels() throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://api.pexels.com/v1/search?query=home&per_page=50&page=1")
                .header("Authorization", "YOUR_API_KEY")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                //Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String mMessage = response.body().string();

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject parent = new JSONObject(mMessage);
                            JSONArray photos = parent.getJSONArray("photos");

                            Log.d("resp", "data"+photos);
                            for (int i = 0; i < photos.length(); i++) {

                                JSONObject data = photos.getJSONObject(i);

                                JSONObject imageUrls = data.getJSONObject("src");
                                ImageModel imageModel = new ImageModel();
                                imageModel.setId(data.getInt("id"));
                                imageModel.setPhotographer(data.getString("photographer"));
                                imageModel.setUrl(imageUrls.getString("medium"));

                                imageModelArrays.add(imageModel);
                            }

                            imagesAdapters.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
}

You need to add your API to request images you get API from there site. In the above code, I am using RecycleView as Gridview with the help of GridLayoutManager.

 GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2, LinearLayoutManager.VERTICAL,false);
 imageList.setLayoutManager(gridLayoutManager);

With the help of GridLayoutManager, we can define no of the column we want to show and pass manager to our RecycleView as shown in the above code.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/imageList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

That’s it hope this above example help you to understand RecyclerView in the android application.