Matthew Vanlandingham
Matthew Vanlandingham

Reputation: 646

Accessing user info from Firebase using model class Android

So I'm working on an app that uses an authorization system to log users in. Whenever a user registers, it updates just fine in my database:

User user = new User(username);
FirebaseDatabase.getInstance().getReference().child("users").child(userid).child("profile").setValue(user);

The problem is, that when I try to access the data again in my next activity to try and get the current user's username, I get this error message:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type friendimals.Model.User

I'm using a basic model class:

public class User {

    private String username;

    public User() {

    }

    public User(String username) {
        this.username= username;

    }


    public String getUsername(){
        return this.username;
    }
}

This is how I'm accessing the information in my database:

mDatabase.child("users").child(mUserId).child("profile").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //This is the line that is causing the crash
                User user = dataSnapshot.getValue(User.class);
                username_TextView.setText(user.getUsername());
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

Any ideas on what this error means and/or how to fix it? Any help is greatly appreciated.

Upvotes: 0

Views: 791

Answers (1)

Benjith Mathew
Benjith Mathew

Reputation: 1221

The problem is you don't have any key called username which you are specified in the model class. dataSnapshot only return the String value.

if your data structure is like this then only that work with model class

userid
|
username:usernameValue

Upvotes: 3

Related Questions