Reputation: 129
I'm creating my first android firebase test project, and facing a problem trying to get back the data. Here is how my data looks like in the console:
and my code to retrieve the age and name:
databaseReference.child("users").child(firebaseUserId).child("profile")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Users users = snapshot.getValue(Users.class);
Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
"Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
and the User(POJO) class looks like this:
public class Users {
String name, gender;
public Users() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
However, I am unable to do this, and the program crashes with this error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type project.ibrapptly.com.kcpe_tests_and_quizzes.Users
How can I get my data back, or what is the most efficient way of doing this?
Upvotes: 0
Views: 671
Reputation: 80944
Change this:
databaseReference.child("users").child(firebaseUserId).child("profile")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Users users = snapshot.getValue(Users.class);
Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
"Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
into this:
databaseReference.child("users").child(firebaseUserId).child("profile")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users users = dataSnapshot.getValue(Users.class);
Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
"Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
You need to remove the for loop in this case. When you are looping you are retrieving the attributes age
and name
which are of type String.
Upvotes: 1