Turan Bus
Turan Bus

Reputation: 1

How to get two variables from Firebase realtime database

static double lat2;

static double lon2;

private void InitMapElements() {

DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("markers");

DatabaseReference zone1Ref = zonesRef.child("m-1"); //database path
DatabaseReference zone1NameRef = zone1Ref.child("latit");

DatabaseReference zone2NameRef = zone1Ref.child("longit");

    zone1NameRef.addValueEventListener(new ValueEventListener() { //reading the first coordinate

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Double lat1 = dataSnapshot.getValue(Double.class);
            lat2 = lat1;
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
        }
    });
    zone2NameRef.addValueEventListener(new ValueEventListener() { //reading the second coordinate
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Double lon1 = dataSnapshot.getValue(Double.class);
            lon2 = lon1;

        }

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

It is not possible to get two variables online and then save it to a static variable from the Firebase realtime database, the variables get the value only once when the method is called. With one variable, everything works fine. The variable changes if you change the value on the base, but with two does not work.

example of working with one variable

Upvotes: 0

Views: 305

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

There is no need to attach two listeners in order to get those two values. A single listener can solve your problem. To solve this, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("markers").child("m-1");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        double lat = dataSnapshot.child("latit").getValue(Double.class);
        double lon = dataSnapshot.child("longit").getValue(Double.class);
        Log.d(TAG, lat + ", " + lon);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
ref.addListenerForSingleValueEvent(valueEventListener);

As you can see, both values are extracted from the DataSnapshot object. Both variables lat and lon will be only be availabe inside the callback, inside onDataChange() due the asynchronous behavior of this method. If you want to use them outiside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Upvotes: 1

Related Questions