Home > Software engineering >  Firebase return null with mvvm
Firebase return null with mvvm

Time:10-27

When I use the code below I can get data from firebase but when I want to access it with MVVM it returns null.

database.collection("Order")
    .get()
    .addOnCompleteListener { it ->
        if (it.isSuccessful) {

            val itemName = it.result.documents[0].data?.get("itemName")
            val id = it.result.documents[0].data?.get("id")

It returns null inside Order.kt. I don't realize what the problem is there. I can't find any similar questions here.

FirebaseOrderService.kt

object FirebaseOrderService {
    private const val TAG = "FirebaseOrderService"
    suspend fun getOrderData(): Order? {
        val db = FirebaseFirestore.getInstance()
        return try {
            db.collection("Order")
                .document().get().await().toOrder()
        } catch (e: Exception) {
            Log.e(TAG, "Error getting order details", e)
            FirebaseCrashlytics.getInstance().log("Error getting order details")
            FirebaseCrashlytics.getInstance().setCustomKey("id", "1")
            FirebaseCrashlytics.getInstance().recordException(e)
            null
        }
    }

SuccessShoppingViewModel.kt

class SuccessShoppingViewModel: ViewModel() {
    private val _orderList = MutableLiveData<Order>()
    val order: LiveData<Order> = _orderList

    init {
        viewModelScope.launch {
            _orderList.value = FirebaseOrderService.getOrderData()
            _orderList
        }
    }

Order.kt

@Parcelize
data class Order(
    val id: String = "",
    val picUrl: String = "",
    val itemName: String = "",
    val itemPrice: Double = 0.0,
    val itemAmount: String = "",
    val itemQuantatiy: Int = 0
) : Parcelable {
    companion object {
        fun DocumentSnapshot.toOrder(): Order? {
            return try {
                val id = getString("id")!!
                val picUrl = getString("picUrl")!!
                val itemName = getString("itemName")!!
                val itemPrice = getLong("itemPrice")?.toDouble()!!
                val itemAmount = getString("itemAmount")!!
                val itemQuantatiy = getLong("itemQuantatiy")?.toInt()!!

                Order(id, picUrl, itemName, itemPrice, itemAmount, itemQuantatiy)
            } catch (e: Exception) {
                Log.e(TAG, "Error converting order", e)
                FirebaseCrashlytics.getInstance().log("Error converting order")
                FirebaseCrashlytics.getInstance().setCustomKey("id", id)
                FirebaseCrashlytics.getInstance().recordException(e)
                null
            }
        }
        private const val TAG = "Order"
    }
}

My Database

CodePudding user response:

You're getting null because of the following line of code:

db.collection("Order")
            .document().get().await().toOrder()

When you are using the above line of code, it means that you are creating a reference to a document with a random ID. Calling CollectionReferenc#document() method, without passing any arguments:

Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.

So what you're actually doing, you're creating a reference that points to a document that doesn't exist. To solve this problem, you have to pass the ID of the document to the document() function like this:

db.collection("Order")
            .document("eBW6...zIO1").get().await().toOrder()
//                                 
  • Related