Search code examples
androidfirebasekotlinfirebase-realtime-databaseany

Firebase fetching data as Kotlin data type Any


I am trying to fetch an entire node in one shot from Firebase Real-time database as type Any. The code that I use is as follows:

val offerDetails = p0.child(querykey).child("Offers").child(offerkey).getValue(Any::class.java)
Log.d("MyMessage", 
offerDetails.toString())

The data is obtained perfectly as the Log returns:

{offer=90, ****ID=********, deliveryHour=0, mobile=******, type=2, deliveryMinute=15, offerComment=******}

However, I am unable to fetch the individual data like the offer, type, etc hereon. Can someone help me out?

P.S. I can get each of the datapoints individually from Firebase. But I am trying to avoid that and instead get the entire node in one shot.


Solution

  • When you are using the following line of code:

    val offerDetails = p0.child(querykey).child("Offers").child(offerkey).getValue(Any::class.java)
    

    The type of the object is Any and not Offer, so you can access its properties. When you are using:

    Log.d("MyMessage", offerDetails.toString())
    

    You are just printing in the logcat the String representation of your offerDetails object. If you need to access its properties, then you should cast that object to an object of type Offer.

    Log.d("MyMessage", (offerDetails as Offer).offer)
    

    In this way, you are telling the compiler that the object is of type Offer and not Any. In this case, the output in the logcat will be:

    90
    

    Edit:

    You can also access the properties using the following line of code:

    val offer = p0.child(querykey).child("Offers").child(offerkey).child("offer").getValue(String::class.java)
    Log.d("MyMessage", offer)
    

    Same output (90) in the logcat.