我想从HashMap<String?, String?>?
获取firebaseDatabase
:
override fun onDataChange(dataSnapshot: DataSnapshot) {
val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>? // todo !!!
if (users != null) {
if (!users.containsKey(userUid)) {
users[userUid] = userName
}
}
}
此代码有效,但Android Studio
在第二行显示警告:
Unchecked cast: Any? to HashMap<String?, String?>?
如何以正确的方式解决这个问题?
答案 0 :(得分:1)
GenericTypeIndicator
的方法有效,谢谢@leoderprofi
val ti = object : GenericTypeIndicator<HashMap<String?, String?>?>() {}
//...
override fun onDataChange(dataSnapshot: DataSnapshot) {
val users: HashMap<String?, String?>? = dataSnapshot.getValue(ti)
if (users != null) {
if (!users.containsKey(userUid)) {
users[userUid] = userName
}
}
}
答案 1 :(得分:0)
您可以使用@Suppress("UNCHECKED_CAST")
(例如)
@Suppress("UNCHECKED_CAST")
val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?