I'm trying to retrieve data from Firebase so I'm using Hashmap for it, but I wanna know why casting Hashmap, why can't use it directly. Please give a deep and easy language answer (should be in Kotlin)
Here is the code:
var map = snapshot.getValue() as Hashmap<String,String>
CodePudding user response:
When called on a DataSnapshot
that contains multiple values, getValue()
returns a Map<String,Object>
since (while the keys are by definition strings) it can't know what types all of the values in your database are.
If you know all the values are strings, you can cast the result to a Map<String,String>
as you do, but it does require you to cast the result you get back from getValue()
.
CodePudding user response:
DataSnapshot#getValue() method returns an object of type Object:
getValue() returns the data contained in this snapshot as native types. The possible types returned are:
- Boolean
- String
- Long
- Double
- Map<String, Object>
- List
Since every node in Firebase Realtime Database can be represented by pairs of keys and values, actually Maps, you have to use that cast in order to actually read the data.
Alternativaly, you can use DataSnapshot#getValue(Class valueType) to map each node into an object of a specific class.