有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓公司。谷歌。火基。数据库DatabaseException:无法转换java类型的对象。字符串以键入com。软件世界。婴儿床。模型。使用者

我是firebase的新手,正在尝试在安卓上实现实时数据库。我可以成功地向数据库写入数据,但当我尝试从数据库读取数据时,我得到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

这就是我在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());
            }
        });

我的用户类如下所示

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;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我认为你应该改变

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

      dbRef.addValueEventListener(new ValueEventListener() {
    

    https://www.firebase.com/docs/android/guide/retrieving-data.html所述

    或者,如果您真的只想获取此特定userId的事件,则获取的DataSnapshot可能已经是您要查找的用户,因此在中使用.getChildren()

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

    可能没有必要