gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:49:58 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com