Tutorial

Android RecyclerView, Android CardView Example Tutorial

Published on August 3, 2022
author

By Anupam Chugh

Android RecyclerView, Android CardView Example Tutorial

Android RecyclerView and Android CardView got introduced in Android Lollipop with Material Design. For those who’re not aware of Material Design, its a comprehensive guide of UI Widgets introduced since Android 5.0 and it improves the visual appeal of the apps.

Android RecyclerView

android recyclerview, android cardview, android cardview example Android RecyclerView is a more advanced, powerful and flexible version of the ListView. Android RecyclerView is similar to ListView except that it forces us to use RecyclerView.ViewHolder class to hold the elements which is not a compulsion in ListView. As the name suggests, Android RecyclerView is used to reuse cells when scrolling up and down by recycling the items in the list. Another improvement in RecyclerView is that it allows us to set the LayoutManagers dynamically at runtime, unlike the ListView which was only available in a Vertical scrolling List. RecyclerView allows us to set the following types of Layouts at runtime.

  • LinearLayoutManager : it supports both vertical and horizontal lists
  • StaggeredLayoutManager : it supports staggered lists
  • GridLayoutManager : it supports displaying grids as seen in GalleryView earlier

Android RecyclerView Classes

  • The RecyclerView.ItemAnimator class provides better support to animating the views unlike the ListViews
  • The RecyclerView.ItemDecorator class provides better support when it comes to adding borders and dividers thereby giving huge control to us

Hence a RecyclerView is more customizable when compared to ListView and gives greater control to the users. The RecyclerView is available in the support library. So we need to modify our gradle script to add the following dependency.

dependencies {
       compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
 }

Android CardView

Android CardView UI component shows information inside cards. This component is generally used to show contact information. This component is available in another support library so we have to add its dependency too.

dependencies {
        compile 'com.android.support:cardview-v7:21.0.0-rc1'
        compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
 }

Android CardView widget allows us to control the background color, shadow, corner radius, elevation etc. For using the custom attributes in XML, we need to add the following namespace declaration to the parent layout. Following is the namespace declaration with some attributes from our project.

<android.support.v7.widget.CardView
        android:id="@+id/card_view"
        xmlns:card_view="https://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardBackgroundColor="@color/grey_300"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true">

The important attributes used above are:

  • card_view:cardCornerRadius : Used to set the corner radius in our layouts
  • card_view:cardBackgroundColor : Used to set the background color of the view

In our example project, we’ll add a RecyclerView to display a list of CardViews that contains Android Version Names and Numbers along with a sample logo. The CardView onclick is programmed to remove that Card from the list. We’ve added a menu option in the ActionBar to add back the removed cards in order. Note: The logo images are taken at random from Google. So sizes would vary.

Android RecyclerView and CardView Example

android recyclerview cardview example, android recyclerview cardview, android cardview, android recyclerview The project consists of a MainActivity that displays the RecyclerView. The CardView is added to the RecyclerView from the CustomAdapter class. The DataModel is used to retrieve the data for each CardView through getters. The MyData class holds the arrays of textviews and drawables along with their ids.

Android RecyclerView and CardView Example Code

The activity_main.xml holds the RecyclerView inside a RelativeLayout as shown below. activity_main.xml code:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@color/grey_300"
    >

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

</RelativeLayout>

Android CardView layout is defined below: cards_layout.xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:tag="cards main container">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        xmlns:card_view="https://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardBackgroundColor="@color/color_white"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true">

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

            <ImageView
                android:id="@+id/imageView"
                android:tag="image_tag"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:src="@drawable/ic_launcher"/>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:layout_weight="2"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textViewName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:text="Android Name"
                    android:textAppearance="?android:attr/textAppearanceLarge"/>

                <TextView
                    android:id="@+id/textViewVersion"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"

                    android:text="Android Version"
                    android:textAppearance="?android:attr/textAppearanceMedium"/>

            </LinearLayout>
        </LinearLayout>

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

</LinearLayout>

Android CardView holds an ImageView along with two TextViews in a Nested Linear Layout. The menu_main.xml contains a single item to add back the cards removed. menu_main.xml code:

<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item android:id="@+id/add_item"
        android:title="Add"
        android:orderInCategory="100"
        app:showAsAction="always"/>
</menu>

The MainActivity.java class is defined below :

package com.journaldev.recyclerviewcardview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;
    private static ArrayList<DataModel> data;
    static View.OnClickListener myOnClickListener;
    private static ArrayList<Integer> removedItems;

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

        myOnClickListener = new MyOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        data = new ArrayList<DataModel>();
        for (int i = 0; i < MyData.nameArray.length; i++) {
            data.add(new DataModel(
                    MyData.nameArray[i],
                    MyData.versionArray[i],
                    MyData.id_[i],
                    MyData.drawableArray[i]
            ));
        }

        removedItems = new ArrayList<Integer>();

        adapter = new CustomAdapter(data);
        recyclerView.setAdapter(adapter);
    }


    private static class MyOnClickListener implements View.OnClickListener {

        private final Context context;

        private MyOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            removeItem(v);
        }

        private void removeItem(View v) {
            int selectedItemPosition = recyclerView.getChildPosition(v);
            RecyclerView.ViewHolder viewHolder
                    = recyclerView.findViewHolderForPosition(selectedItemPosition);
            TextView textViewName
                    = (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
            String selectedName = (String) textViewName.getText();
            int selectedItemId = -1;
            for (int i = 0; i < MyData.nameArray.length; i++) {
                if (selectedName.equals(MyData.nameArray[i])) {
                    selectedItemId = MyData.id_[i];
                }
            }
            removedItems.add(selectedItemId);
            data.remove(selectedItemPosition);
            adapter.notifyItemRemoved(selectedItemPosition);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.add_item) {
           //check if any items to add
            if (removedItems.size() != 0) {
                addRemovedItemToList();
            } else {
                Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    }

    private void addRemovedItemToList() {
        int addItemAtListPosition = 3;
        data.add(addItemAtListPosition, new DataModel(
                MyData.nameArray[removedItems.get(0)],
                MyData.versionArray[removedItems.get(0)],
                MyData.id_[removedItems.get(0)],
                MyData.drawableArray[removedItems.get(0)]
        ));
        adapter.notifyItemInserted(addItemAtListPosition);
        removedItems.remove(0);
    }
}

The removeItems() method is invoked from the listener method to remove the CardView clicked. Its respective id is stored in an array to retrieve later. To add the view later we’ve implemented another method named addRemovedItemToList(). In this method, we add that view at a predefined position in the list and remove its id from the removedItems array. The CustomAdapter is notified in both the cases. The CustomeAdapter.java class is defined below :

package com.journaldev.recyclerviewcardview;

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 java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

    private ArrayList<DataModel> dataSet;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textViewName;
        TextView textViewVersion;
        ImageView imageViewIcon;

        public MyViewHolder(View itemView) {
            super(itemView);
            this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
            this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
        }
    }

    public CustomAdapter(ArrayList<DataModel> data) {
        this.dataSet = data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cards_layout, parent, false);

        view.setOnClickListener(MainActivity.myOnClickListener);

        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

        TextView textViewName = holder.textViewName;
        TextView textViewVersion = holder.textViewVersion;
        ImageView imageView = holder.imageViewIcon;

        textViewName.setText(dataSet.get(listPosition).getName());
        textViewVersion.setText(dataSet.get(listPosition).getVersion());
        imageView.setImageResource(dataSet.get(listPosition).getImage());
    }

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

In the above code, we’ve implemented our own ViewHolder by extending RecyclerView.ViewHolder. The view is inflated from the cards_layout.xml which we had defined in the layouts directory. The onClickListener in the MainActivity is attached to this view in the below snippet.

view.setOnClickListener(MainActivity.myOnClickListener);

An ArrayList stores all the data in the form of a DataModel class object in an ArrayList and adds them to the respective cards in the list. The DataModel.java and MyData.java class which contains the data specific to this application are given below :

package com.journaldev.recyclerviewcardview;

public class DataModel {

    String name;
    String version;
    int id_;
    int image;

    public DataModel(String name, String version, int id_, int image) {
        this.name = name;
        this.version = version;
        this.id_ = id_;
        this.image=image;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public int getImage() {
        return image;
    }

    public int getId() {
        return id_;
    }
}
package com.journaldev.recyclerviewcardview;

public class MyData {

    static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow"};
    static String[] versionArray = {"1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};

    static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
            R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
            R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh};

    static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}

Below is the output produced by our android RecyclerView and CardView example application. android recyclerview, android cardview, android cardview example, android recyclerview example As you can see the removed item is always added at the third index (fourth position in the list) This brings an end to this tutorial about android RecyclerView and CardView. You can download the Android RecyclerView CardView Example Project from the below link.

Download Android RecyclerView CardView Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 21, 2016

Thanks a lot! This is the only guide which worked.

- Usman

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 23, 2017

m getting dataset error in customAdapter class…can anyone help?

- Anaya

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 2, 2016

    Thanks it’s help me.

    - Gaurav

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 29, 2016

      How to place “add” button in topview .plz explain

      - N.chandu

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 13, 2016

      Android CardView holds an ImageView along with two TextViews in a Nested Linear Layout. The menu_main.xml contains a single item to add back the cards removed. menu_main.xml code:

      - Bejo

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 19, 2016

      How to show cardview alongwith button in Recyclerview ?

      - Tikam Prajapati

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 30, 2016

        How to add border color to card view

        - Ather Sajjad

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 15, 2016

          Great! Thank you

          - Ron

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 22, 2017

            For those having too much gap in b/w cards change in cards_layout.xml android:layout_height=“match_parent” to android:layout_height=“wrap_content”

            - Rupanshu

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 17, 2017

              how to use a RelativeLayout instead of Image in the cards

              - Shubham Kumar Gupta

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 25, 2017

                When i switch b/w different apps, it overlaps my cardlayout items why?

                - Asad Mukhtar

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 3, 2017

                  Having the RecyclerView as a Private Static is giving me a warning on memory leaks, what is the workaround to this?

                  - Jim

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 31, 2017

                    Thank you so much , this is the greatest and most perfect tutorial for recycleview and cardview .

                    - Faria

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      December 9, 2017

                      great tutorial

                      - bonnie

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        January 12, 2018

                        how to display images that are stored in internal storage in recyclerview with cardview?

                        - vinayak

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 15, 2018

                          Thank you so much , this is the greatest and most perfect tutorial for recyclerview and cardview

                          - kanchan

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            February 18, 2018

                            Small correction : In the cards_layout.xml , the root linear layout’s height needs to be ‘wrap_content’ instead of ‘match_parent’

                            - Dreming Droid

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              February 23, 2018

                              Thank you very much for the tutorial! Here are notes of the modifications I had to make in Android Studio 3.0.1 : ------------------------ Gave an error: card_view:cardBackgroundColor=“@color/grey_300” error is “Error:error: resource color/grey_300 (aka com.blah.testapplication:color/grey_300) not found.” To fix this, had to add the grey_300 entriy to app/res/values/colors.xml : https://stackoverflow.com/questions/27974783/using-the-colors-for-the-new-material-design-theme-in-android Also change from this: card_view:cardBackgroundColor=“@color/color_white” to this : card_view:cardBackgroundColor=“@color/white” ------------------------ In cards_layout.xml, this line can be changed, apparently mipmap is the new preferred way to do multi-sized app icons: from: android:src=“@drawable/ic_launcher”/> to : android:src=“@mipmap/ic_launcher”/> ------------------------ Can confirm what Dreming Droid said about the cards_layout.xml: “the root linear layout’s height needs to be ‘wrap_content’ instead of ‘match_parent’”. Without this, the cards have a massive gap between them when testing on Android Studio 3.0.1. ------------------------ I also added entries for Nougat and Oreo, just to have more data to play with, in MyData.java : static String[] nameArray = {“Cupcake”, “Donut”, “Eclair”, “Froyo”, “Gingerbread”, “Honeycomb”, “Ice Cream Sandwich”,“JellyBean”, “Kitkat”, “Lollipop”, “Marshmallow”, “Nougat”, “Oreo” }; static String[] versionArray = {“1.5”, “1.6”, “2.0-2.1”, “2.2-2.2.3”, “2.3-2.3.7”, “3.0-3.2.6”, “4.0-4.0.4”, “4.1-4.3.1”, “4.4-4.4.4”, “5.0-5.1.1”,“6.0-6.0.1”, “7.0-7.1.2”, “8.0-8.1” }; static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics, R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh, R.drawable.nougat, R.drawable.oreo }; static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; I then got two images off google for nougat.png and oreo.png. However the image sizes were much bigger than the others, so it made them have massive cards. To prevent this, also made the following to change to cards_layout.xml, under the <ImageView : From: android:layout_height=“wrap_content” To : android:layout_height=“match_parent” That made all the entries display the same. -------------------------- It’s my first Android project, so I wanted to make these edits from scratch, so I made a fresh project + files as per the article + the edits here + copied the PNG files to the drawable folder. However the “Add” button and the bar with the app name are not showing. Is there some trick to get them to show, or some other change needed that’s not mentioned in the article?

                              - Nick J

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              February 25, 2018

                              Nice observation Nick. Obviously, you need to add the grey_300 color code in the colors.xml as it it rightly mentioned in the source code too!

                              - Anupam Chugh

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              December 18, 2019

                              Anupam Sir some people say that this code not working but i am using that i did not have any problem i guessed people are doing mistake in Android / androidx features xml binding error Appcompact toolbar missing that all reason is Android / AndroidX features thanks sir You are very helpful for me thanks alot

                              - Ashish Vishwakarma

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                June 22, 2018

                                My app is crashing here is the error : 06-22 17:40:35.803 6766-6766/com.example.shahvrun.recyclerdemo E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.shahvrun.recyclerdemo, PID: 6766 android.view.InflateException: Binary XML file line #4: Binary XML file line #4: Error inflating class layout Caused by: android.view.InflateException: Binary XML file line #4: Error inflating class layout Caused by: java.lang.ClassNotFoundException: Didn’t find class “android.view.layout” on path: DexPathList[[zip file “/data/app/com.example.shahvrun.recyclerdemo-1/base.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_dependencies_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_0_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_1_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_2_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_3_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_4_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_5_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_6_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_7_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_8_apk.apk”, zip file “/data/app/com.example.shahvrun.recyclerdemo-1/split_lib_slice_9_apk.apk”],nativeLibraryDirectories=[/data/app/com.example.shahvrun.recyclerdemo-1/lib/x86, /system/lib, /vendor/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:380) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at android.view.LayoutInflater.createView(LayoutInflater.java:609) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:700) at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:68) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) at android.view.LayoutInflater.inflate(LayoutInflater.java:495) at android.view.LayoutInflater.inflate(LayoutInflater.java:426) at com.example.shahvrun.recyclerdemo.CustomAdapter.onCreateViewHolder(CustomAdapter.java:40) at com.example.shahvrun.recyclerdemo.CustomAdapter.onCreateViewHolder(CustomAdapter.java:14) at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6685) at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5869) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2232) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1559) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1519) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:614) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3529) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4082) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) 06-22 17:40:35.806 6766-6766/com.example.shahvrun.recyclerdemo E/AndroidRuntime: at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585) at android.widget.LinearLayout.onLayout(LinearLayout.java:1494) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at com.android.internal.policy.DecorView.onLayout(DecorView.java:724) at android.view.View.layout(View.java:17523) at android.view.ViewGroup.layout(ViewGroup.java:5612) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2342) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2069) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871) at android.view.Choreographer.doCallbacks(Choreographer.java:683) at android.view.Choreographer.doFrame(Choreographer.java:619) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

                                - V

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                December 18, 2019

                                android.support.design.widget.CoordinatorLayout Replace this code androidx.support.design.widget.CoordinatorLayout error Binary XML file line #4: Error inflating class layout also removed

                                - Ashish Vishwakarma

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  July 30, 2018

                                  Hi, first of all excelent article, but if you don’t mind can you help me please? I followed every part part of the tutorial but when i run the app i got the next error: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference at com.example.charlie.pizzas.CustomAdapter.onBindViewHolder(CustomAdapter.java:55) the line 55 is the next: textViewVersion.setText(dataSet.get(listPosition).getName()); i cand understand the error but i don’t know why im getting the erro, if you could help me i will appreciate a lot. Best regards

                                  - Charlie

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  July 30, 2018

                                  Hi Charlie, I haven’t seen your code but this looks like an issue in the resource linking. Make sure that you are using the correct row layout and inflating it correctly in the Adapter. Please make sure that you’ve properly initialized the TextView as well since that is what is NULL in your stack trace above. Thanks

                                  - Anupam Chugh

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 24, 2018

                                    When i gave to action on image its crashing why i dont no can you send me the code on custom adapter to give action on particular image. This is my code check this public void onBindViewHolder(final MyViewHolder holder, final int listPosition) { TextView textViewName = holder.textViewName; TextView textViewVersion = holder.textViewVersion; ImageView imageView = holder.imageViewIcon; LinearLayout parentLayout=holder.parent_layout; textViewName.setText(dataSet.get(listPosition).getName()); textViewVersion.setText(dataSet.get(listPosition).getVersion()); imageView.setImageResource(dataSet.get(listPosition).getImage()); parentLayout.setTag(dataSet.get(listPosition).getId()); holder.parent_layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (listPosition == 0) { //Toast.makeText(mContext,“cliked 1 image”,Toast.LENGTH_SHORT).show(); Intent i = new Intent(mContext, Yoga1Activity.class); mContext.startActivity(i); } }

                                    - Bharat Kumar

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 25, 2018

                                    Can you the paste the crash log/exception you are getting?

                                    - Anupam Chugh

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      January 9, 2019

                                      Important: There is a small writing mistake in a portion where you explained the CustomAdapter class, The CustomerAdapter.java class is defined below :. Please write ‘CustomAdapter.java’ instead of “CustomerAdapter.java”

                                      - K Sajid

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        January 24, 2019

                                        great job man it’s nicely work for me

                                        - UdR

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          July 16, 2019

                                          sir, new version pie dependencies give me.

                                          - rahil kanani

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          July 19, 2019

                                          implementation ‘com.android.support:recyclerview-v7:29.0.0’ implementation ‘com.android.support:cards_layout-v7:29.0.0’

                                          - Chandan

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            July 19, 2019

                                            Migrate to AndroidX.

                                            - Anupam Chugh

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 4, 2019

                                              this error show java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.Object android.content.Context.getSystemService(java.lang.String)’ on a null object reference at android.view.LayoutInflater.from(LayoutInflater.java:238) at .Adapter.onCreateViewHolder(Adapter.java:47) holder.imageView.setImageDrawable(mCtx.getApplicationContext().getResources().getDrawable(model.getImage()));

                                              - Anup

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                November 12, 2019

                                                This code not work for me .It shows error .My android version is 3.4.1

                                                - Ganesan

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                November 15, 2019

                                                Can you please post the error you’re getting?

                                                - Anupam Chugh

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  January 22, 2020

                                                  can someone please upload the androidx version of this that actually works? I made some modifications to mine and removed all errors, but the app crashes on emulator. It doesn’t give any error so I have no idea what’s going on

                                                  - doruk

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  August 9, 2020

                                                  HI, i have uploaded androidx version of this turorial at https://github.com/naseebjoon/RecyclerViewCardView\_androidx

                                                  - Naseeb Joon

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    March 21, 2020

                                                    How Do I do onItemClick In this ?

                                                    - John Melody Melissa Cindy

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 31, 2020

                                                      Thank Bro, you Awsome!

                                                      - Mindada

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        March 17, 2021

                                                        Gradle project sync failed. Pls help.

                                                        - Caleb Kiragu

                                                          Join the Tech Talk
                                                          Success! Thank you! Please check your email for further details.

                                                          Please complete your information!

                                                          Become a contributor for community

                                                          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                          DigitalOcean Documentation

                                                          Full documentation for every DigitalOcean product.

                                                          Resources for startups and SMBs

                                                          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                          Get our newsletter

                                                          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                          New accounts only. By submitting your email you agree to our Privacy Policy

                                                          The developer cloud

                                                          Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                          Get started for free

                                                          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                          *This promotional offer applies to new accounts only.