简体   繁体   中英

Get value from list of objects Firebase Android Studio

I have the following code:

    public void signOn(String id, String password){
        usersReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                boolean valid = false;
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                    String key = singleSnapshot.getKey();
                    if (key.equals(id)) {
                        singleSnapshot.getValue()//THIS LINE THIS LINE
                        Intent myIntent = new Intent(WelcomePage.this, MainActivity.class);
                        myIntent.putExtra("key", key);
                        WelcomePage.this.startActivity(myIntent);
                    }
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

    }

When I call singleSnapshot.getValue() , I get {password=passwordExample, username=usernameExample} as those are the keys and their values in my Realtime Database. How can I access the password value and the username value?

One way to get it as HashMap and extract value from it, like this.

Map<String, String> map = (Map<String, String>) singleSnapshot.getValue();
String username = (String) map.get("username"); // You should pass exact key names here.
String password = (String) map.get("password");

The DataSnapshot#getValue() returns an object of type Object . It's true you can cast it to a Map<String, Object>, as GowthamKK mentioned in his answer but there is by far a simpler solution that would get the value according to the corresponding type. So in code, it would be as simple as:

String password = singleSnapshot.child("password").getValue(String.class);

As you can see I have used now, <T> getValue(@NonNull Class<T> valueType ) which:

This method is used to marshall the data contained in this snapshot into a class of your choosing.

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