gpt4 book ai didi

java.lang.ClassCastException : java. util.ArrayList 无法转换为 Firebase 实时数据库中的 java.util.Map

转载 作者:行者123 更新时间:2023-12-02 11:23:40 24 4
gpt4 key购买 nike

使用 Firebase 实时数据库:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map in Firebase Realtime database at line getUpdateData((Map)dataSnapshot.getValue());*

Firebase 数据库结构如下:

Click here

这就是我所做的:

public ArrayList<NewsModel> alNotificationModel;

DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReference().child("notification");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
getUpdateData((Map<String, Object>) dataSnapshot.getValue());
pb1.setVisibility(View.GONE);
}

@Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});

private void getUpdateData(Map<String, Object> users) {
final ArrayList<NewsModel> alNotificationModel = new ArrayList<>();
for (Map.Entry<String, Object> entry : users.entrySet()) {
NewsModel notificationModel = new NewsModel();
Map singleUser = (Map) entry.getValue();

notificationModel.setNotificationId((Long) singleUser.get("notId"));
notificationModel.setNotificationTitle((String) singleUser.get("notTitle"));
notificationModel.setNotificationDescription((String) singleUser.get("notDescription"));

alNotificationModel.add(notificationModel);
}
}

最佳答案

要解决此类问题,首先您必须了解 Firebase 的工作原理。就像在当前场景中,firebase 会给你 List 这就是你得到 ClassCastException 的原因,因为你在数据库中输入的数据,即系列 1,2...等等这里我正在谈论数据中的键,如果您使用某些前缀更改这些键,比如 not_1not_2...等等,它肯定会返回一个 HashMap 字符串和对象类型。请尝试该场景并告诉我。否则,如果您不想更改数据库结构,可以在提取数据时检查数据快照是否是列表或 HashMap 的实例。这是reference对于您面临的同样问题,希望这个可以帮助您,同时我没有任何其他引用可以让您更好地理解,我一定会添加到这个答案

This is how i had achieved

关于java.lang.ClassCastException : java. util.ArrayList 无法转换为 Firebase 实时数据库中的 java.util.Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746925/

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