I am trying to get users location using Geo fire for android. I was trying to get the users longitude and latitude and save it in the firebase database, but I had no luck.
Below is my code. Can someone tell me what I'm doing wrong?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_registration);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
savebutton=findViewById(R.id.save);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference update = rootRef.child("Users").child(uid);
GeoFire geoFire=new GeoFire(rootRef);
geoFire.getLocation("location", new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
if(location!=null){
Double longi = location.longitude;
Double lat = location.latitude;
update.child("longitude").setValue(longi);
update.child("latitude").setValue(lat);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
In GeoFire you can set and query locations by string keys. To set a location for a key simply call the setLocation method:
geoFire.setLocation("location", new GeoLocation(37.7853889, -122.4056973), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, FirebaseError error) {
if (error != null) {
System.err.println("There was an error saving the location to GeoFire: " + error);
} else {
System.out.println("Location saved on server successfully!");
}
}
});
After setting the location, you can then retrieve it and save the values to the database:
geoFire.getLocation("location", new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude, location.longitude))
// save longitude and latitude to db
Double longi = location.longitude;
Double lat = location.latitude
} else {
System.out.println(String.format("There is no location for key %s in GeoFire", key));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.err.println("There was an error getting the GeoFire location: " + databaseError);
}
});