Home > Software design >  How can I store and retrieve latitude and longitude values from Firebase?
How can I store and retrieve latitude and longitude values from Firebase?

Time:01-23

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) {
            
        }
    });

CodePudding user response:

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);

CodePudding user response:

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);            
  •  Tags:  
  • Related