muoki_D muoki_D - 1 month ago 16
Android Question

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.softworld.crib.models.User

I am new to firebase and am trying to implement the realtime database on android. I can write to the db succesfully but when i try to read from the db, I get

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.softworld.crib.models.User


Here is my DB on firebase

This is how I post and read from the DB

DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("myUsers");
String userId = dbRef.push().getKey();

User user = new User("My New Name","mynewemail@gmail.com",loggedInUser.getPersonPhoto());
//how I post to db
dbRef.child(userId).setValue(user);
//how I read from db
dbRef.child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
List users = new ArrayList<>();

for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
User user = noteDataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, user.getPersonEmail(), Toast.LENGTH_LONG).show();
users.add(user);
}

//Log.d(TAG, "Value is: " + value);
}

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


And my User class looks like this

public class User {
String personName,personEmail;
Uri personPhoto;

public User() {
}

public User(String personName, String personEmail, Uri personPhoto) {
this.personName = personName;
this.personEmail = personEmail;
this.personPhoto = personPhoto;
}

public String getPersonName() {
return personName;
}

public void setPersonName(String personName) {
this.personName = personName;
}

public String getPersonEmail() {
return personEmail;
}

public void setPersonEmail(String personEmail) {
this.personEmail = personEmail;
}

public Uri getPersonPhoto() {
return personPhoto;
}

public void setPersonPhoto(Uri personPhoto) {
this.personPhoto = personPhoto;
}
}

Answer

I think you should change

  dbRef.child(userId).addValueEventListener(new ValueEventListener() {

to

  dbRef.addValueEventListener(new ValueEventListener() {

as explained in https://www.firebase.com/docs/android/guide/retrieving-data.html

Alternatively, if you really want to only get an event for this particular userId, the DataSnapshot your getting is probably already the user you're looking for, so using .getChildren() in

  for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {

is probably unnecessary.

Comments