使用Firebase实时数据库:
java.lang.ClassCastException:java.util.ArrayList无法强制转换为Firebase实时数据库中的java.util.Map,行getUpdateData((Map)dataSnapshot.getValue()); *
Firebase数据库结构在这里:
这就是我所做的:
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);
}
}
答案 0 :(得分:1)
要解决此类问题,首先要了解firebase的工作原理。就像在当前场景中一样,firebase会给你List,这就是你得到ClassCastException
的原因,因为你在数据库中输入的数据,即系列1,2 ......等等这里我说的是你的密钥数据,如果你用一些前缀更改这些键,可以说 not_1 , not_2 ....等等它肯定会返回一个String的hashmap和对象类型。请尝试这种情况并告诉我。否则,如果您不想更改数据库结构,则可以在提取数据时检查数据快照是列表实例还是散列映射实例。这是reference同样的问题,你面临的希望这个问题可以帮助你并且我并没有任何其他的参考让你更好地理解,我一定会加入这个答案
答案 1 :(得分:0)
要解决此问题,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notificationRef = rootRef.child("notification");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<NewsModel> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
NewsModel newsModel = ds.getValue(NewsModel.class);
list.add(newsModel);
}
//Do what you need to do with this list
Log.d("TAG", list.toString()); //To see is not emplty
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
notificationRef.addListenerForSingleValueEvent(valueEventListener);