【问题标题】:How to convert Firebase array in to collection in android如何将Firebase数组转换为android中的集合
【发布时间】:2016-03-13 06:51:44
【问题描述】:
firebase=new Firebase("https://flickering-inferno-4404.firebaseio.com/User/awosome");
    firebase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String temp=dataSnapshot.getValue().toString();
            GenericTypeIndicator<List<User>> t=new GenericTypeIndicator<List<User>>(){};
            List<User> userList=dataSnapshot.getValue(t);
            if (userList!=null){
                userList.get(0).getBirthYear();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

而用户模型是

public class User {
private int birthYear;
private String fullName;
public User() {}
public User(String fullName, int birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
}
public long getBirthYear() {
    return birthYear;
}
public String getFullName() {
    return fullName;
}

}

但是在List&lt;User&gt; userList=dataSnapshot.getValue(t); 在线我遇到了类似的错误

致命异常:主要 进程:com.chhota.firebasepractice,PID:8233 com.firebase.client.FirebaseException:无法反弹输入 在 com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:210) 在 com.chhota.firebasepractice.MainActivity$1.onDataChange(MainActivity.java:40) 在 com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:56) 在 com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45) 在 com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38) 在 android.os.Handler.handleCallback(Handler.java:733)

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    你在the location you query有这个JSON结构:

    {
      "-KCdZSoPFJ91-VKCA4pq" : {
        "birthYear" : 1912,
        "fullName" : "Alan Turing"
      },
      "-KCdZSoeKEYo96gb2GBF" : {
        "birthYear" : 1913,
        "fullName" : "Mohmad"
      }
    }
    

    下次请将此添加到您的问题中,以便人们有足够的信息继续。

    由于您使用的是ValueEventListener,因此您将在onDataChange() 回调中获取整个JSON。这不是用户的List,而是将键(-KCdZSoPFJ91-VKCA4pq 等)映射到用户的Map

    所以:

    GenericTypeIndicator<Map<String, User>> t=new GenericTypeIndicator<Map<String, User>>(){};
    Map<String, User> userMap=dataSnapshot.getValue(t);
    for (User user: userMap.values()) {
        System.out.println(user.getBirthYear());
    }
    

    【讨论】:

    • 这里有点奇怪,一个 Map 是一个无序集合,但是 firebase 查询支持“order by”子句,这意味着它们是有序的,这怎么能工作?
    • 如果你想保持顺序,你应该遍历孩子:for (DataSnapshot child: dataSnapshot.getChildren()) { ...。也可以在此处查看文档中的示例:firebase.google.com/docs/database/android/…
    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多