Skip to content
Advertisement

Java Get Value from Object by Key Name

I have retrieved an object from Firebase and would like to access the values of it using the name of each field I would like the value for. In javascript, this would be something as simple as myObject.name to retrieve the name in the object.

How can I do the equivalent in Java?

mDatabase = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
userId = user.getUid();

ValueEventListener myObjectListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.i(TAG, "getting data");
        Object myObject = dataSnapshot.getValue();

        Log.v(TAG, myObject.toString()); 
        // Outputs: {name= "john doe", hair="brown", isStudent=true, age=12} 

        // HERE is where I would like to get the name.
        // DOES NOT work. Have also attempted things like
        // myObject.getString("name"), etc.
        myObject.getClass().getFieldName("name") 
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
    }
};

mDatabase.child("users").child(userId).addValueEventListener(myObjectListener);

Advertisement

Answer

Try this:

@SuppressWarnings("unchecked")
Map<String, Object> user = (Map<String, Object>) dataSnapshot.getValue();
String name = (String) user.get("name");
String hair = (String) user.get("hair");
long age    = (Long)   user.get("age");
...

If you have a properly defined User class, than this would work even better:

User user = dataSnapshot.getValue(User.class);
String name = user.getName();
String hair = user.getHair();
...

Finally, there is a third option as well (using DataSnapshot.child(String) method):

String name = (String) dataSnapshot.child("name").getValue();
String hair = (String) dataSnapshot.child("hair").getValue();
...
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement