简体   繁体   中英

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?

PS 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.

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 no t 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.

Firebase Supported Data Types

Your object is most likely returning as a Map<String, Object> object. Maybe use the map as you can read/write it better than an Any object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM