M.Baraka M.Baraka - 1 year ago 170
Android Question

Firebase query hashmap to class

I'm using firebase, and I'm doing some query to get the data, and then I'm using

I also tried
to get the result . The response from
is a

I found that each key in that
(in first case) represents the field in my class.

Is there a faster way to convert that
to my class\model? or do I have to do it custom for each class I have?.
I found in LINK that I can use
, however, it throws

My experience with reflection is very little, but I understand in theory I can use it, but not sure how, so if possible an example would appreciated.


Trip model for example (not all of it of course just to view it)

public class Trip implements Model
private String ID;
private String driverID;

private LatLng addressFrom;
private LatLng addressTo;

private List<LatLng> locationList;

private boolean isActive;

response is like this (while debugging)

result = {HashMap@830043578728} size = 14
0 = {HashMap$HashMapEntry@830043579944} "fullAddress" -> "this is the address"
1 = {HashMap$HashMapEntry@830043579176} "addressFrom" -> " size = 2"
2 = {HashMap$HashMapEntry@830043581632} "state" -> "0"
3 = {HashMap$HashMapEntry@830043579552} "distanceMeter" -> "706"
4 = {HashMap$HashMapEntry@830043580000} "id" -> "-KX5Ihn7E_g8HEmsXXL3"
5 = {HashMap$HashMapEntry@830043579744} "duration" -> "157"
6 = {HashMap$HashMapEntry@830043581864} "timeMilliSeconds" -> "1479722067649"
7 = {HashMap$HashMapEntry@830043579664} "driverID" -> "RZZplHcojGWRoJdRH2SOswQvSBO2"
8 = {HashMap$HashMapEntry@830043579472} "addressTo" -> " size = 2"
9 = {HashMap$HashMapEntry@830043581520} "locationList" -> " size = 3"
10 = {HashMap$HashMapEntry@830043580080} "length" -> "706"
11 = {HashMap$HashMapEntry@830043578880} "active" -> "false"
12 = {HashMap$HashMapEntry@830043581576} "passengerCount" -> "1"
13 = {HashMap$HashMapEntry@830043579800} "endAddressText" -> "this is the end address text"

EDIT 2 (exception from getValue(Trip.lass)

com.google.firebase.database.DatabaseException: Class com.google.android.gms.maps.model.LatLng is missing a constructor with no arguments

Answer Source

I think the error is occurring because some classes like LatLng cannot be stored in Firebase directly. Looking at this sample app by google, when the location data is sent to Firebase, the getLatitude() and getLongitude() values are used instead of the LatLng class. So if you use something like List of HashMaps from Lat to Long to store your location data, you can use dataSnapshot.getValue(Trip.class) to parse it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download