Android Studio Examples

100+ tutorials, source code, and examples to help you develop creative and technical skills.

How to retrieve data from firebase in RecyclerView android

AndroidManifest.xml

<!--    adding Internet permissions-->
    <uses-permission android:name="android.permission.INTERNET"/>

gradle.build (project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        // always use latest version of dependencies
        classpath "com.android.tools.build:gradle:4.1.3"
        classpath 'com.google.gms:google-services:4.3.10'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

gradle.build (app)

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 32
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.learnoset.firebasetutorials"
        minSdkVersion 19
        targetSdkVersion 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.+'

    // Firebase Bom Dependency
    implementation platform('com.google.firebase:firebase-bom:29.0.3')

    // Firebase Realtime Dependency
    implementation 'com.google.firebase:firebase-database'

    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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 {

    // getting Firebase Database reference to communicate with firebase database
    private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    // creating List of MyItems to store user details
    private final List<MyItems> myItemsList = new ArrayList<>();

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

        // getting RecyclerView from xml file
        final RecyclerView recyclerView = findViewById(R.id.recyclerView);

        // setting recyclerview size fixed for every item in the recyclerview
        recyclerView.setHasFixedSize(true);

        // setting layout manager to the recyclerview. Ex. LinearLayoutManager (vertical mode)
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                // clear old items / users from list to add new data/ users
                myItemsList.clear();

                // getting all children from users root
                for (DataSnapshot users : snapshot.child("users").getChildren()) {

                    // to prevent app crash check if the user has all the details in Firebase Database
                    if (users.hasChild("fullname") && users.hasChild("mobile") && users.hasChild("email")) {

                        // getting users details from Firebase Database and store into the List one by one
                        final String getFullname = users.child("fullname").getValue(String.class);
                        final String getMobile = users.child("mobile").getValue(String.class);
                        final String getEmail = users.child("email").getValue(String.class);

                        // creating user item with user details
                        MyItems myItems = new MyItems(getFullname, getMobile, getEmail);

                        // adding this user item to List
                        myItemsList.add(myItems);
                    }
                }

                // after all the users has added to list.
                // now set adapter to RecyclerView
                recyclerView.setAdapter(new MyAdapter(myItemsList, MainActivity.this));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

MyAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

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

    private final List<MyItems> items; // items array list
    private final Context context; // context

    // constructor
    public MyAdapter(List<MyItems> items, Context context) {
        this.items = items;
        this.context = context;
    }

    @NonNull
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_adapter_layout, null));
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {

        // getting single item / user details from List
        MyItems myItems = items.get(position);


        // setting user details to TextViews
        holder.fullname.setText(myItems.getFullname());
        holder.mobile.setText(myItems.getMobile());
        holder.email.setText(myItems.getEmail());
    }

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

    // MyViewHolder class to hold view reference for every item in the RecyclerView
    // We will learn more about this in RecyclerView tutorials series
    static class MyViewHolder extends RecyclerView.ViewHolder {

        // declaring 3 TextViews
        private final TextView fullname, email, mobile;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            // getting TextViews from recyclerview_adapter_layout.xml file
            fullname = itemView.findViewById(R.id.fullnameTV);
            email = itemView.findViewById(R.id.emailTV);
            mobile = itemView.findViewById(R.id.mobileTV);
        }
    }
}

MyItems.java

public class MyItems {

    private final String fullname, mobile, email;

    public MyItems(String fullname, String mobile, String email) {
        this.fullname = fullname;
        this.mobile = mobile;
        this.email = email;
    }

    public String getFullname() {
        return fullname;
    }

    public String getMobile() {
        return mobile;
    }

    public String getEmail() {
        return email;
    }
}

Projects with Source Code + Video Tutorials

You can download our Java and Android Studio Projects with Source Code and Video Tutorials.

Custom-Navigation-bar-with-Material-UI-design
Custom Navigation bar with Material UI design
Settings-and-Profile-page-UI-design-in-Android-Studio-with-Example-and-Source-Code
Settings and Profile page UI design in Android Studio with Example and Source Code
How-to-create-custom-Update-Dialog-with-Example-in-Android-Studio
How to create custom Update Dialog with Example in Android Studio

If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com

Follow us to learn Coding and get in touch with new Technologies.