Home > Software design >  How to get Each value from Firebase?
How to get Each value from Firebase?

Time:07-15

How can I get each value from Firebase and set it to my variable (Lat&Long)

My Code :

            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference reference = database.getReference();
            reference.child("Hutan").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//                        String Bude = snapshot.getValue().toString();
                        String Lat = snapshot.child("Lat").getValue().toString();
                        String Long = snapshot.child("Long").getValue().toString();
                        LatLng Bude = new LatLng(Double.valueOf(Lat), Double.valueOf(Long));
//                        googleMap.addMarker(new MarkerOptions().position(Bude).title("Curug Dago!"));
//                        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Bude, 17));
                        Log.e("TAG", "Location: "   Bude);
                    }

                }

and Firebase

The log result said LOG CAT

CodePudding user response:

Since you're using Java, here is the code that can help you read the value of Lat, as well the value of Long:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference hutanRef = db.child("Hutan");
hutanRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            double lat = snapshot.child("Lat").getValue(Double.class);
            double lng = snapshot.child("Long").getValue(Double.class);
            Log.d("TAG", lat   ", "   lng);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

As you can see, there is no need for any loop. You can directly access both values. The result in the logcat will be:

-6.858573273779082, 107.630600755386

P.S. Try to find reasonable field names, as Long in the database might be confused with the Long class. So you can use latitude and longitude, or even simpler, lat and lng.

  • Related