简体   繁体   中英

How to Get 1 Data of 3 Data in Firebase Android Studio

I have 3 data with diffrent ID in firebase.

Example :

Data :
  - ABC 
     Lat: 12345
     Lng: 23124
  - DEF 
     Lat: 23324
     Lng: 43553
  - GHI 
     Lat: 23424
     Lng: 12343

How can i get Lat which is 12345 from ID ABC , i wish i could show it with Toast trigger by Button.

From your snapshot you have to get your child and your element just like this :

private FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("Data"); //Init your ref at Data
myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {                       
            String lat = messageSnapshot.child("ABC").child("Lat").getValue().toString(); //acces to ABC => Lat
            Toast.makeText(getApplicationContext(), "Lat: " + lat, Toast.LENGTH_SHORT).show() //print here
        }

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

To toast a message that contains the lat value, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference abcRef = rootRef.child("Data").child("ABC");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        double lat = dataSnapshot.child("Lat").getValue(Double.class);
        Toast.makeText(getApplicationContext(), "Lat: " + lat, Toast.LENGTH_SHORT).show()
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
abcRef.addListenerForSingleValueEvent(valueEventListener);

The output will be: 12345

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM