Firebase Cloud Firestore Android

Related tags

App FirebaseSports
Overview

Firebase Cloud Firestore Android

📜 Description

Android app built to demonstrate on how to build RecyclerView using Cloud Firestore with Collections, Documents and Fields.

App
\_____ MainActivity    ->   Display recycler view list using FirestoreAdapter.
\_____ DetailActivity  ->   Show user selected items details.   

An abstract class implements EventListener to listen SnapshotQuery changes.

abstract class FirestoreAdapter<VH : RecyclerView.ViewHolder>(
    private val query: Query
) : RecyclerView.Adapter<VH>(), EventListener<QuerySnapshot> {
    // Override class members here.
}

onEvent will be called with the new value or the error if an error occurred.

override fun onEvent(
    documentSnapshots: QuerySnapshot?,
    exception: FirebaseFirestoreException?
) {
    // Dispatch the event
    for (change in documentSnapshots!!.documentChanges) {
        // Snapshot of the changed document
        when (change.type) {
            // New Document was added to set of documents matching query.
            DocumentChange.Type.ADDED -> onDocumentAdded(change)
            // New document within the query was modified.
            DocumentChange.Type.MODIFIED -> onDocumentModified(change)
            // Removed, deleted, no longer matches the query.
            DocumentChange.Type.REMOVED -> onDocumentRemoved(change)
        }
    }
}

Create a snapshot variable for ArrayList of type DocumentSnapshot, this variable has all document snapshots which we will work with.

private val snapshots = ArrayList<DocumentSnapshot>()

Each time changes are made we use their index for doing it correctly, and lastly we notify those changes with index.

protected open fun onDocumentAdded(change: DocumentChange) {
    snapshots.add(change.newIndex, change.document)
    notifyItemInserted(change.newIndex)
}

protected open fun onDocumentModified(change: DocumentChange) {
    if (change.oldIndex == change.newIndex) {
        // Item changed but remained in same position
        snapshots[change.oldIndex] = change.document
        notifyItemChanged(change.oldIndex)
    } else {
        // Item changed and changed position
        snapshots.removeAt(change.oldIndex)
        snapshots.add(change.newIndex, change.document)
        notifyItemMoved(change.oldIndex, change.newIndex)
    }
}

protected open fun onDocumentRemoved(change: DocumentChange) {
    snapshots.removeAt(change.oldIndex)
    notifyItemRemoved(change.oldIndex)
}

Now we need functions which listens to those document changes, we call this functions in our activity and fragments whenever we need to get data. Create a variable with name registration of type ListenerRegistration which listens to the query using SnapshotListener.

var registration: ListenerRegistration? = null

open fun startListening() {
    if (registration == null) {
        registration = query.addSnapshotListener(this)
    }
}

open fun stopListening() {
    if (registration != null) {
        registration!!.remove()
        registration = null
    }

    snapshots.clear()
}

Listen to changes in SnapshotQuery from Activity in onStart() and onStop().

open fun startListening() {
    if (registration == null) {
        registration = query.addSnapshotListener(this)
    }
}

open fun stopListening() {
    if (registration != null) {
        registration!!.remove()
        registration = null
    }

    snapshots.clear()
}

Blog

These implementations are clearly demonstrated in my blog.

License

Copyright 2021 Rajasekhar K E

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
A android plant shop app with firebase backend
A android plant shop app with firebase backend

PlantShop A android plant shop app with firebase backend What i learned: Create a responsive UI with ConstraintLayout Store product and save to user c

Projeto de Prova Semestral. Aplicativo Android com login e registro utilizando Firebase Authentication e consumo de API com Retrofit.
Projeto de Prova Semestral. Aplicativo Android com login e registro utilizando Firebase Authentication e consumo de API com Retrofit.

Ocean-Tech-Android Projeto de Prova Semestral. Aplicativo Android com login e cadastro utilizando Firebase Authentication e consumo de API com Retrofi

A Modular Firebase plugin (Android) for godot

GDFirebase GDFirebase is a Modular Godot Plugin for using Firebase Depends on Godot game engine: git clone https://github.com/godotengine/godot Avail

E-commerce android app using firebase and kotlin
E-commerce android app using firebase and kotlin

RSHLN_App e-commerce android app using firebase and kotlin. Images -

FirebaseAuthentication - Login/Register Android Application using Firebase Authentication

FireBaseAuthentication This is a Firebase Authentication Application which will

Firebase Authentication and realtime database implementation in Android Kotlin

Androidfirebaseauthentication Firebase is Google’s mobile platform that helps you develop high-quality apps and provides hosted backend services such

FireApp is an open-source project that is built around Firebase Products, especially for learning purposes
FireApp is an open-source project that is built around Firebase Products, especially for learning purposes

FireApp is an open-source project that is built around Firebase Products, especially for learning purposes. This application is written entirely in Kotlin using Android Architecture Components and MVVM architecture pattern. You'll see in the code of this repo, how Firebase Products are working together.

Book Parking is a demo application based on MVVM architecture. The app allows users to booking parking slots, the app uses firebase for the backend.
Book Parking is a demo application based on MVVM architecture. The app allows users to booking parking slots, the app uses firebase for the backend.

Book Parking is a demo application based on MVVM architecture. The app allows users to booking parking slots, the app uses firebase for the backend.

Google map location tracker uploading current to realtime database and displaying location information from firebase realtime.

WEEK-8-SQ009-ANDROID LOCATION - GROUP WORK (2) Problem Description Track your partner(s). Implementation 1: You are to build a map application to show

Owner
null
✨ Social network app made with Android Compose, full Kotlin, Firebase Authentication, Storage and Firestore 🚀

Your friends, for real. Share daily random moments with your friends and discover who they really are. ✨ Instant Instant is a social media actually un

Vincent Guillebaud 58 Dec 23, 2022
Post It is the android App for uploading posts and liking them using Firebase and FireStore.

Post-it Post It is the android App for uploading posts and liking them using Firebase and FireStore. This app also uses DAO, RecycleView, Coroutines a

Anubhav Shishodia 1 Apr 12, 2022
To learn how to build an e-commerce app for Android using the Firestore database from Google Firebase Technology

It is an adjustable e-commerce application that you can use to create your own online store or use it as a template to create an e-commerce app for your client. In this app we are covering such topics as Firebase basics how to upload and download data to and from an online database Displaying Images from the Cloud Creating User Profiles Uploading and displaying Products Building a Cart System Selecting images from your phone

Makaota 2 Jun 25, 2022
WatchStore Ecommerce app using MVVM, Kotlin, Firebase Firestore, Coroutines, Dagger Hilt

WatchStore Sanple App Like Ecommerce App Developed using Kotlin. Features used: Firebase Firestore Navigation Component. MVVM Architecture RecyclerVie

Ketan Bhangale 20 Oct 26, 2022
A ToDo application that I used Firebase Authentication and Firestore.

ToDoApp With the To-Do Application, you can create notes to your list, update them or delete them. You can change its colors as you like and mark it e

Feyza Ãœrkut 11 Nov 18, 2022
Android SMS receiver with firestore and Jetpack compose

Android SMS Receiver Android SMS receiver with firestore and Jetpack compose App

Hakan Meral 2 Sep 14, 2022
MEGA Android Client - A fully-featured client to access your Cloud Storage provided by MEGA

A fully-featured client to access your Cloud Storage provided by MEGA. This document will guide you to build the application on a Linux machine with Android Studio.

Mega Limited 1.1k Jan 3, 2023
ì‹ ê²½ - Cloud-native messaging/pubsub with powerful routing

신경 신경 /ɕʰinɡjʌ̹ŋ/ • sin-gyeong (try it with IPA Reader) nerve Nerve /nərv/ • noun (in the body) a whitish fiber or bundle of fibers that transmits imp

amy null 75 Dec 22, 2022
Simple Android app during a coding night. Just Learning Firebase and Android

KUI-App Simple Android app during a coding night. Just Learning Firebase and Android What we learned: Some basics of Android Basic setup of Firebase:

Kibabii University Informatics Club (KUI) 7 Aug 28, 2022
Clone of real world Chatting application Whatsapp built on Android Studio and Firebase

Clone of real world Chatting application Whatsapp built on Android Studio and Firebase

Aditya Bonde 11 May 23, 2022