Armazenando dados no Firebase com Android — Cloud Firestore

Quem falou que aplicações simples precisam de um super backend?

Daivid Vasconcelos Leal
Jul 6 · 7 min read
Image for post
Image for post


Overview sobre NoSql

Image for post
Image for post
Estrutura de dados recomendada pelas diretrizes da Google no uso do Cloud Firestore.
Image for post
Image for post
Estrutura criada no Cloud Firestor.

Agora sim… Cloud Firestore!

implementation "com.google.firebase:firebase-firestore:21.2.1"
val networkModule = module {
single{
FirebaseAuth.getInstance()
}

single {
val fireStore = FirebaseFirestore.getInstance()
fireStore.firestoreSettings = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build()
fireStore
}

...

}

val repositoryModule = module {
...
single { Service(get(), get()) as ServiceContract}
...
}
class Service(private val auth: FirebaseAuth, private val database: FirebaseFirestore) :
ServiceContract {
...}

Criando uma Estrutura de Conteúdo

override fun signUp(
name: String,
birthday: Timestamp,
email: String,
password: String,
success: (FirebaseUser?) -> Unit,
error: (Exception?) -> Unit
) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val id = auth.currentUser?.uid?.let {
it
}
?: run { email }
database.collection(COLLECTION_USER).document(id).set(
User(
name = name,
birthday = birthday,
email = email,
providerId = auth.currentUser?.providerId,
uId = auth.currentUser?.uid
)
).addOnSuccessListener {
success(auth.currentUser)
}.addOnFailureListener{
error(it)
}
} else {
error(task.exception)
}
}
}
database.collection(COLLECTION_USER).document(id).set(
User(
name = name,
birthday = birthday,
email = email,
providerId = auth.currentUser?.providerId,
uId = auth.currentUser?.uid
)
).addOnSuccessListener {
success(auth.currentUser)
}.addOnFailureListener{
error(it)
}

Recuperando dados

database.collection(COLLECTION_USER).document(uid).get().addOnSuccessListener {
success(it.toObject(User::class.java))
}.addOnFailureListener {
error(it)
}
override fun insertTrainingDiary(
date: String,
trainingDiary: TrainingDiary,
success: () -> Unit,
error: (Exception?) -> Unit
) {
auth.currentUser?.uid?.let { uid ->
database
.collection(COLLECTION_TRAINING_DIARY)
.document(uid)
.collection(COLLECTION_DIARY)
.document(date).set(trainingDiary)
.addOnSuccessListener {
success()
}
.addOnFailureListener {
error(it)
}
}
?: run {
error(Exception())
}
}
database
.collection(COLLECTION_TRAINING_DIARY)
.document(uid)
.collection(COLLECTION_DIARY)
.document(date)
.get()
.addOnSuccessListener {
success(it.toObject(TrainingDiary::class.java))
}
.addOnFailureListener {
error(it)
}
database
.collection(COLLECTION_TRAINING_DIARY)
.document(uid)
.collection(COLLECTION_DIARY).get()
.addOnSuccessListener {
success(it.toObjects(TrainingDiary::class.java))
}
.addOnFailureListener {
error(it)
}

Filtros

database
.collection(COLLECTION_TRAINING_DIARY)
.document(uid)
.collection(COLLECTION_DIARY)
.whereGreaterThanOrEqualTo(FieldPath.documentId(), startDate)
.whereLessThanOrEqualTo(FieldPath.documentId(), endDate)
.get()
.addOnSuccessListener {
success(it.toObjects(TrainingDiary::class.java))
}
.addOnFailureListener {
error(it)
}

Deletando conteúdo

override fun deleteTrainingDiary(
date: String,
trainingDiary: TrainingDiary,
success: () -> Unit,
error: (Exception?) -> Unit
) {
auth.currentUser?.uid?.let { uid ->
database
.collection(COLLECTION_TRAINING_DIARY)
.document(uid)
.collection(COLLECTION_DIARY)
.document(date).delete()
.addOnSuccessListener {
success()
}
.addOnFailureListener {
error(it)
}
}
?: run {
error(Exception())
}
}

Concluindo

Concrete

Nós desenvolvemos produtos digitais com inovação, agilidade…

Daivid Vasconcelos Leal

Written by

Currently Master Student at UFRPE in Applied Computer Science with the field Quantum Computer, and Android Developer at Concrete Solutions.

Concrete

Concrete

Nós desenvolvemos produtos digitais com inovação, agilidade e excelentes práticas, para que o mercado brasileiro e latino-americano acompanhe a velocidade do mercado digital mundial.

Daivid Vasconcelos Leal

Written by

Currently Master Student at UFRPE in Applied Computer Science with the field Quantum Computer, and Android Developer at Concrete Solutions.

Concrete

Concrete

Nós desenvolvemos produtos digitais com inovação, agilidade e excelentes práticas, para que o mercado brasileiro e latino-americano acompanhe a velocidade do mercado digital mundial.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store