将DataSnapshot转换为类对象
我是Firebase数据库的新手,并且正在关注Google的文档以从我的数据库中检索数据.
我有这个结构:
I'm newbie to Firebase Database and I'm following Google's Docs to retrive data from my database.
I have this structure:
root/
|
|--- 82JWZZZd***
| |
| |--- profile
| |
| |--- id: 1
| |--- name: Arnold Schwarzenegger
| |--- age: 70
|
|--- GB3FDPiw***
|
|--- profile
|
|--- id: 1
|--- name: Sylvester Stallone
|--- age: 71
我想检索用户的个人资料信息,并且有一个Java类:
I want to retrive the profile information of a user and I have a Java class:
public class Profile{
private int id;
private String name;
private int age;
public Profile(){
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public Profile(int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
}
因此,正如我从Google文档中了解到的那样,我创建了一个侦听器:
So, as I learned from Google's Docs I create a Listener:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(getUid() + "/profile");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getContext(), "" + dataSnapshot.getValue(),
Toast.LENGTH_LONG).show();
// Profile prf = dataSnapshot.getValue(Profile.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
烤面包给我看: {id = 1,name = Arnold Schwarzenegger,年龄= 71}
但是,如果我取消注释该行
The Toast show me this:{id=1, name=Arnold Schwarzenegger, age=71}
BUT if I uncomment the line
Profile prf = dataSnapshot.getValue(Profile.class);
我的应用程序崩溃.
my App CRASH.
我不了解Google文档的区别.有人可以帮我吗?我为此太苦了!
错误是:
I don't understand the difference with Google documentation. Can somebody help me? I'm struggling with this too much!
Error is:
com.google.firebase.database.DatabaseException: Class com.companyname.myApp.FirstFragment$Profile is missing a constructor with no arguments
如果您有私有字段,则需要添加getter和setter.如果您不想使用设置方法和获取方法,请使用公共字段.
If you have private fields, you need to add getters and setters. If you don't want setters and getters, use public fields.
此外,由于您的Profile类嵌套在片段中,因此您需要将其标记为 static
.因此,公共静态类Profile {
.另请参阅有关Github的评论: https://github.com/firebase/FirebaseUI-Android/issues/46#issuecomment-167373575
Additionally, since your Profile class is nested inside your fragment, you'll need to mark it as static
. So public static class Profile{
. Also see this comment on Github: https://github.com/firebase/FirebaseUI-Android/issues/46#issuecomment-167373575