无法从 android 中的 firebase 读取数据

2024-05-24

我正在开发 Android 应用程序Firebase用于维护移动后端。我有这种格式的数据库Firebase

{
  "users" : {
    "-Kh2wjxeT-w26opA0yqe" : {
      "email" : "[email protected] /cdn-cgi/l/email-protection",
      "firstName" : "XX",
      "interest" : {
        "interests" : [ "Cricket", "Table Tennis", "Football" ]
      },
      "lastName" : "XXX",
      "password" : "abcd@1234"
    }
  }
}

用户.java

@IgnoreExtraProperties
public class User {

    public String firstName;
    public String lastName;
    public String email;
    public String password;

    public Interest interest;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String firstName, String lastName, String email, String password, Interest interest) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.interest = interest;
    }
}

兴趣.java

public class Interest {

    public List<String> interests;

    public Interest() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public Interest(List<String> interests) {
        this.interests = interests;
    }
}

我已经添加了addValueEventListener以这种方式对儿童“用户”

mDatabase.child("users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
            User user = dataSnapshot.getValue(User.class);
            Log.d("Scheduled", user.firstName + user.lastName + user.interest.interests.toString());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
    }
});

它正在获取我所拥有的正确数据Firebase但它没有映射数据Usersjava 对象,所以当我无法访问值时。我不确定我在这里犯了什么错误。

Log.d("已安排", user.firstName + user.lastName + user.interest.interests.toString());


为了显示数据,您需要像这样更改代码:

mDatabase.child("users").child(userId).addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
        String firstName = dataSnapshot.child("firstName").getValue(String.class); 
        Log.d("Scheduled", firstName); 
    } 

    @Override 
    public void onCancelled(DatabaseError error) { 
    // Failed to read value 
    } 
});   

其中userId是由生成的唯一IDpush() method.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法从 android 中的 firebase 读取数据 的相关文章

随机推荐