简体   繁体   中英

How do i put dataSnapshot into a HashMap and Iterate Firebase Android

I am trying to turn a DataSnapshot object to HashMap then iterate it for accessing latitude longitude and avatar values for each player. Because after this i will use those values to render markers on map.

db

Another question is is it possible to exclude users itself from the query ? I mean is it possible to write mydb.child("map").child("players").notequalto(username).addValueEventList... Or do i have to exclude it with code after pulling the data?

    mydb.child("map").child("players").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                HashMap<String,Object> players= new HashMap();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                players.put(childSnapshot.getKey(), childSnapshot.getValue());
            }
                    Log.d("players",dataSnapshot.getValue().toString());





            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

output:

 D/players: {lifesuxtr={lat=40.8901741, long=29.3772963, avatar =petyr}, lastpeony={lat=40.89, long=29.37, avatar=dino}}

Assuming that the map node is a direct child of your Firebase database root, to get those values, please the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference playersRef = rootRef.child("map").child("players");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Map<Double, Double> players = new HashMap<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            double lat = ds.child("lat").getValue(Double.class);
            double long = ds.child("long").getValue(Double.class);
            Log.d("TAG", lat + " / " + long);
            players.put(lat, long);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
playersRef.addListenerForSingleValueEvent(eventListener);

The output will be:

40.89 / 29.37
40.89 / 29.37

Having there values, you can now add your markers. And answering to your question, no, you cannot use negation in a query. There is no notEqualTo() method in Firebase.

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