How can I store and retrieve latitude and longitude values from Firebase?

My code needs Latitude, Longitude to be stored and retrieved.

Now, this code does retrieve data but in form of string which I tried to convert to float by typecasting method but the app crashes.

HashMap<String,Object>  value= new HashMap<>();
    value.put("Lat",23);
    value.put("Lng",88);
DatabaseReference db;
    db = FirebaseDatabase.getInstance().getReference().child("Location");
db.setValue(value);

 db.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String var = snapshot.child("Lat").getValue(Object.class).toString();
            String var2 = snapshot.child("Lng").getValue(Object.class).toString();
            Toast.makeText(getApplicationContext(),var,  Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            
        }
    });

Solution 1:

To convert a String to a Float you can use Float.parseFloat() or Float.valueOf()

example:

String lat = "34.12345";
float latitude = Float.parseFloat(lat);

Solution 2:

How can I store and retrieve integer values from Firebase?

To store the latitude and longitude you need to store double values and not integers. To achieve that, please use the following lines of code:

HashMap<String, Object> location = new HashMap<>();
location.put("lat", 23.11885844); 👈 double value
location.put("lng", 88.12435566); 👈 double value

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference locationRef = db.child("location");
locationRef.setValue(location).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", "Location written successfully.");
        } else {
            Log.d("TAG", task.getException().getMessage());
        }
    }
});

As you can see, I have also attached a listener to see when the location is successfully written in the database.

To read the data back, please use the following lines of code:

locationRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String lat = snapshot.child("lat").getValue(Double.class);
            String lng = snapshot.child("lng").getValue(Double.class);
            Log.d("TAG", lat + ", " + lng);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

And the result in the logcat will be:

23.11885844, 88.12435566