java - 如何将 Firebase 数组转换为 Android 中的集合

标签 java android firebase firebase-realtime-database

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<User> userList=dataSnapshot.getValue(t);我收到类似的错误

FATAL EXCEPTION: main Process: com.chhota.firebasepractice, PID: 8233 com.firebase.client.FirebaseException: Failed to bounce to type at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:210) at com.chhota.firebasepractice.MainActivity$1.onDataChange(MainActivity.java:40) at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:56) at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45) at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38) at android.os.Handler.handleCallback(Handler.java:733)

最佳答案

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

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

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

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

所以:

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

关于java - 如何将 Firebase 数组转换为 Android 中的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35967447/

相关文章:

android - 声音录制

android - 如何将文件添加到 Android 项目,然后使用 NDK 加载它

java - 在为图像集成 firebase 数据引用时,我遇到了下面提到的错误

android - Firebase 如何在 android 中处理 linkWithCredential "ERROR_CREDENTIAL_ALREADY_IN_USE"

java - 添加已发布的convertSendAndReceive确认

java - 如何将 HashMap 的值映射到单选按钮

java - 获取错误 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure

java - java中如何处理父类(super class)构造函数抛出的异常?

android - eclipse如何知道你的项目名称?

android - Firebase token 身份验证错误