Ad

How To Loop Through Data In Map With Java

Fetched data from Firebase database and added as a Map object. now I need to loop through every key's value so I can get child data from it. here are my both Database structure and the code am using:

enter image description here

    public void gettingStationDate() {
    // Read from the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("station");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
            Log.e(TAG, "Value is: " + map);
            assert map != null;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Log.e("The Result", entry.getKey() + "/" + entry.getValue());

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
    }

this code give me the result as key, value like this : -LlRGuwBNe2-S_MHn2DW/{station_longitude=30.854333, station_name=الاصلاح الزراعى, station_latitude=29.313847, station_geohash=stjyy07mw14h} Now what i need to do is to get the inner values of the shown values , as statin_longitude , station_name etc..

Ad

Answer

Since each child node that you have is another JSON object, each value in your Map is another Map. And since all your values are strings, this time it's a Map<String,String>.

So to get the specific values, you'd do something like:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
    assert map != null;
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        Log.i("The key", entry.getKey());
        Map<String,String> values = (Map<String,String>) entry.getValue();
        Log.i("station_name", map.get("station_name"));
    }
}

It is more idiomatic to use the DataSnapshot's method to accomplish the same:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    for (DataSnapshot stationSnapshot: dataSnapshot.getChildren()) {
        Log.i("The key", stationSnapshot.getKey());
        Log.i("station_name", stationSnapshot.child("station_name").getValue(String.class));
    }
}
Ad
source: stackoverflow.com
Ad