-1

I have no idea how to save location in Firebase without using Geofire. One possible method may be to save only the co-ordinates to Firebase but looking at the location object (of Android), it has so many properties along with the coordinates. How to save complete object and retrieve it later?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Ashu.mkb
  • 1
  • 2

1 Answers1

1

You can achieve this, following these steps. First create a model class that looks like this:

public class LocationModel {
    private double lat, lng;

    LocationModel() {}

    public LocationModel(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }

    public double getLat() { return lat; }
    public double getLng() { return lng; }
}

Create an object of the class and add it to the database like this:

LocationModel locationModel = new LocationModel(48.858383, 2.294480);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference locationOneRef = rootRef.child("locations").child("locationOne");
locationOneRef.setValue(locationModel);

Your database should look like this:

Firebase-root
   |
   --- locations
          |
          --- locationOne
                  |
                  --- lat: 48.858383
                  |
                  --- lng: 2.294480

And to get the data back, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference locationOneRef = rootRef.child("locations").child("locationOne");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        double lat = dataSnapshot.child("lat").getValue(Double.class);
        double lng = dataSnapshot.child("lng").getValue(Double.class);
        Log.d("TAG", lat + / " + lng);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
locationOneRef.addListenerForSingleValueEvent(valueEventListener);

The output will be:

48.858383 / 2.294480
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193