Recyclerview with Cardview | Firebase database is the real-time database which is store data in JSON format and immediately synchronizes on every all platform. Firebase Database is used to read and write the write the database. Firebase supports multiple platforms i.e. ios, Android, PHP. Firebase Realtime Database is a cloud hosted, NoSQL.

RecyclerView is the upgraded version of the listview. It is more flexible and advanced version. It can easily be Animate. Let’s Display the Firebase Database in Recyclerview.

Output Result:-

Wants to Learn Android application development with firebase from Scratch

1. Create firebase project by Clicking on “CREATE NEW PROJECT”. Now Enter the project name of your choice I named it “FirebaseRecyclerviewCardview”. select your country name. press “Create Project” Now Click on “Add firebase to your Android app”. Now popup shows which ask you to enter a package name. meanwhile, Create a project in android Studio name it “firebase”. now enter the package name in the popup shown in the browser(enter the exact package name otherwise it will not connect to the app). you can enter App nickname(optional). Now download the google-services.json file. copy this file and Move the google-services.json file you just downloaded into your Android app module root directory.

2. Now open Project-level build.gradle (<project>/build.gradle).

buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.0.0'
  }
}

open App-level build.gradle (<project>/<app-module>/build.gradle).

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

Click on “FINISH” button.

3. Now inside app-level build.gradle file update firebase database dependency.

compile 'com.google.firebase:firebase-database:10.0.1'

4. Now Change the Realtime database rules

before:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

After:

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

5. Add Recyclerview and Cardview Dependency in-app level build.gradle file.

compile 'com.android.support:recyclerview-v7:25.1.1'

compile 'com.android.support:cardview-v7:25.1.1'

6. create or update the activity_main.xml file(layout>activity_main.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:id="@+id/activity_main"
    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="com.mytrendin.firebaserecyclerviewcardview.MainActivity">

    <Button
        android:text="View"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/view"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycle"
        android:layout_below="@+id/view"></android.support.v7.widget.RecyclerView>
</RelativeLayout>

7. Add [media-downloader media_id=”771″ texts=”res folder”] to add all images files and some decorative xml files .

8. Add card.xml file in layout folder

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="140dp"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:scaleType="fitXY"
                android:src="@drawable/falls"
                />

            <TextView
                android:id="@+id/vname"
                android:layout_width="match_parent"
                android:text="name"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:paddingTop="@dimen/album_title_padding"
                android:textColor="@color/album_title"
                android:textSize="@dimen/album_title"
                android:layout_toLeftOf="@+id/vaddress"
                android:layout_toStartOf="@+id/vaddress" />

            <TextView
                android:id="@+id/vemail"
                android:text="email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/vname"
                android:paddingBottom="@dimen/songs_count_padding_bottom"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:textSize="@dimen/songs_count"
                android:layout_alignRight="@+id/vname"
                android:layout_alignEnd="@+id/vname" />

            <ImageView
                android:id="@+id/overflow"
                android:layout_width="@dimen/ic_album_overflow_width"
                android:layout_height="@dimen/ic_album_overflow_height"
                android:layout_alignParentRight="true"
                android:layout_below="@id/thumbnail"
                android:layout_marginTop="@dimen/ic_album_overflow_margin_top"
                android:scaleType="centerCrop"
                android:src="@drawable/menu" />

            <TextView
                android:text="TextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:id="@+id/vaddress" />

        </RelativeLayout>

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

</LinearLayout>

9.  Add a model java file name it FireModel.java

package com.mytrendin.firebaserecyclerviewcardview;

/**
 * Created by csa on 3/7/2017.
 */

public class FireModel {

    public String name;
    public String email;
    public String address;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Related:

Drag and Swipe with RecyclerView

Best security tips for android phone

Periodically send GPS location to Firebase with custom time frame in Android

Android Firebase working with Realtime Database and Storage

How to use android Firebase Invites in application

Best free music app for android

7 Best Free Android Emulators

Watch Video

10. Add Recycler view Adapter file in Java folder name it RecyclerAdapter.java

package com.mytrendin.firebaserecyclerviewcardview;

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.TextView;

import java.util.List;

/**
 * Created by csa on 3/7/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{

    List<FireModel> list;
    Context context;

    public RecyclerAdapter(List<FireModel> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
        MyHoder myHoder = new MyHoder(view);


        return myHoder;
    }

    @Override
    public void onBindViewHolder(MyHoder holder, int position) {
        FireModel mylist = list.get(position);
        holder.name.setText(mylist.getName());
        holder.email.setText(mylist.getEmail());
        holder.address.setText(mylist.getAddress());
    }

    @Override
    public int getItemCount() {
        
        int arr = 0;
        
        try{
            if(list.size()==0){
              
                arr = 0;
                
            }
            else{

                arr=list.size();
            }

            
            
        }catch (Exception e){



        }

        return arr;
        
    }

    class MyHoder extends RecyclerView.ViewHolder{
        TextView name,email,address;


        public MyHoder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.vname);
            email= (TextView) itemView.findViewById(R.id.vemail);
           address= (TextView) itemView.findViewById(R.id.vaddress);

        }
    }

}

11. Now Create or Edit MainActivity.java file

package com.mytrendin.firebaserecyclerviewcardview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

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

public class MainActivity extends AppCompatActivity {

    FirebaseDatabase database;
    DatabaseReference myRef ;
    List<FireModel> list;
    RecyclerView recycle;
    Button view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view = (Button) findViewById(R.id.view);
        recycle = (RecyclerView) findViewById(R.id.recycle);
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("message");

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                list = new ArrayList<FireModel>();
                for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                    FireModel value = dataSnapshot1.getValue(FireModel.class);
                    FireModel fire = new FireModel();
                    String name = value.getName();
                    String address = value.getAddress();
                    String email = value.getEmail();
                    fire.setName(name);
                    fire.setEmail(email);
                    fire.setAddress(address);
                    list.add(fire);

                }

            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w("Hello", "Failed to read value.", error.toException());
            }
        });


        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {




                RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
                RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
               /// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
               // recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
                recycle.setLayoutManager(recyce);
                recycle.setItemAnimator( new DefaultItemAnimator());
                recycle.setAdapter(recyclerAdapter);




            }
        });


    }
}

11. AndroidManifest.xml file will remain the same.


you really liked the article, please subscribe to our YouTube Channel for videos related to this article. Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts