Android - Cannot Retrieve Data From Firebase
Solution 1:
Your code is almost right, but I think it's the saving of the data that's letting it down. When you load the data back from the database you're marshalling the data into a Route
instance:
Route route = dataSnapshot.getValue(Route.class);
This will expect a locations
node under each child to match setLocations(ArrayList<Location>)
in your POJO class. Instead, the data it retrieves is the ArrayList
directly.
When saving your location list, you'll need to arrange the structure such that the list of locations are stored under $schoolName/routes/$routeId/locations
:
So, when saving your route point data, you'll need to do:
database.child(schoolName).child("routes").child(routeId).child("locations").setValue(points);
An easy way to think of this would be: if the Route
also had a name field (setName(String)
) then the database may also have $schoolName/routes/$routeId/name
in the same place as the locations
value.
Alternatively, when saving to the database, you could convert your points
variable to a Route
instance and then push that directly to $schoolName/routes/$routeId
instead, which will ensure that it's stored correctly.
Solution 2:
Try this
final HashMap<Integer,HashMap<String,Double>> positions = new HashMap<>();
userRef.child(sharedPreferences.getString("school", null)).child("routes").child(sh.getString("key",null)).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
publicvoid onDataChange(DataSnapshot dataSnapshot) {
int i=0;
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
HashMap<String,Double> position = new HashMap<String, Double>();
position.put("lat",Double.parseDouble(postSnapshot.child("latitude").getValue().toString()));
position.put("lng",Double.parseDouble(postSnapshot.child("longitude").getValue().toString()));
positions.put(i++,position);
}
}
You can access the values stored in positions
variable as
positions.get(index).get("lat");
positions.get(index).get("lng");
Post a Comment for "Android - Cannot Retrieve Data From Firebase"