Home > Software engineering >  Сan't get data from Firestore, no errors
Сan't get data from Firestore, no errors

Time:06-09

I'm trying to get data from the Firestore. The code below, mostly taken from the docs doesn't get anything from the database, although writing data works without issue.

Code from fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    init()
}

private fun init() {
    db = FirebaseFirestore.getInstance()
    mFirestoreRef = db.collection("users").document(USER_ID).collection("deals")
    val viewModel = ViewModelProvider(this).get(DealsViewModel::class.java)
    viewModel.retriveData(mFirestoreRef)
    recyclerView = binding.rcView
    adapter = TradeNoteAdapter()
    recyclerView.adapter = adapter
    var notes = viewModel.getAllNotes()
    adapter.setList(notes)
}

Code from ViewModel:

import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.google.firebase.firestore.CollectionReference
import space.timur.tradenotefirebase.APP
import space.timur.tradenotefirebase.model.TradeNoteModel

class DealsViewModel : ViewModel() {

private var notes: ArrayList<TradeNoteModel> = ArrayList()

fun retriveData(firestoreReference: CollectionReference){
    firestoreReference.get()
        .addOnSuccessListener { documents ->
            for(document in documents){
                var note = document.toObject(TradeNoteModel::class.java)
                notes.add(note)
            }
        }.addOnFailureListener{ e->
            Toast.makeText(APP, e.message, Toast.LENGTH_SHORT).show()
        }
}

fun getAllNotes(): ArrayList<TradeNoteModel> {
    return notes
}

}

CodePudding user response:

That's not how you should deal with Firestore. All Firebase APIs are asynchronous, so there is no way you can simply return notes, as a result of a method. To solve this, you can use a custom callback as explained in this answer, or since you're using Kotlin, you might also consider using Kotlin Coroutines, as explained in this answer.

Besides that, I highly recommend you read this article:

Where I have explained four ways in which you can deal with Firestore.

  • Related