HashMap为null,因此我无法从Firebase数据库中的模拟器中显示我的数据 [英] HashMap is null so i cant get my data shown in the emulator from Firebase database

查看:63
本文介绍了HashMap为null,因此我无法从Firebase数据库中的模拟器中显示我的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android studio显示了警告,因此使用ALT + ENTER代码

Android studio showed a warning so with ALT + ENTER the code

 val name = data[USERNAME] as String

成为

val name = data?.get(USERNAME) as String

但是我的模拟器仍然崩溃

but my emulator is still crashing

 thoughtsCollectionRef.get()
.addOnSuccessListener { snapshot -> 
for(document in snapshot.documents){
val data = document.data 

//this is my code after listening to android studio 

val name = data?.get(USERNAME) as String
val timestamp = data?.get(TIMESTAMP) as Date
val thoughtTxt = data?.get(THOUGHT_TXT) as String
val numLikes = data?.get(NUM_LIKES) as Long
val numComments = data?.get(NUM_COMMENTS) as Long
 val documentId = document.id

//我用safecall ?.get()编辑了其他所有变量,但仍然崩溃

//I edited every other variable with the safecall ?.get() and its still crashing

 val newThought = Thought(name,timestamp,thoughtTxt,numLikes.toInt(),numComments.toInt(),
                    documentId)


thoughts.add(newThought)
}

 thoughtsAdapter.notifyDataSetChanged()

推荐答案

data?.get(TIMESTAMP)调用返回如果要以Date对象结尾,则可以使用Timestamp方法toDate():

If you want to end up with a Date object, you can use the Timestamp method toDate():

val date = timestamp?.toDate()

还请注意,在这种情况下,应使用安全的转换运算符as?代替as:

Also note that you should use a safe casting operator as? instead of as in this case:

val name = data?.get(USERNAME) as? String
val timestamp = data?.get(TIMESTAMP) as? Timestamp
val thoughtTxt = data?.get(THOUGHT_TXT) as? String
val numLikes = data?.get(NUM_LIKES) as? Long
val numComments = data?.get(NUM_COMMENTS) as? Long

data?.get(KEY)可能会产生一个null对象,该对象不能强制转换为任何类型,并且该操作将导致崩溃.

The data?.get(KEY) may produce a null object, which can't be cast to any type and the operation will result in a crash.

这篇关于HashMap为null,因此我无法从Firebase数据库中的模拟器中显示我的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆