我希望能够访问我的集合的字段值,但是我无法在for循环中执行此操作。
我已附上我尝试过的代码和下面的屏幕截图。
在下面的代码中,str是文档中的名称(例如:sgjj,如屏幕截图所示)
firestore数据库的屏幕截图:
我尝试的代码:
class HostActivityScreen : AppCompatActivity(),HostAdapter.OnItemCheckListener {
var currentSelected:ArrayList<String> = ArrayList()
override fun onItemCheck(item: String) {
currentSelected.add(item)
}
override fun onItemUncheck(item: String) {
currentSelected.remove(item)
}
for(str in currentSelected){
print(str)
var id: String = ""
var gamingname:String=""
mFirestore.collection("AllUsers").document(str).get().addOnCompleteListener(OnCompleteListener<DocumentSnapshot> { task ->
if (task.isSuccessful) {
val docs:DocumentSnapshot= task.result!!
print(docs.getData())
if(docs!=null){
id =task.result!!.data!!.get("gaminguserid").toString()
gamingname = task.result!!.data!!.get("gaminname").toString();
}
}
})
}
}
它显示的错误是:
kotlin.KotlinNullPointerException
at HostActivityScreen$onCreate$1$5.onSuccess(HostActivityScreen.kt:120)
at HostActivityScreen$onCreate$1$5.onSuccess(HostActivityScreen.kt:31)
at com.google.android.gms.tasks.zzn.run(Unknown Source)
第120行是:
id= documentSnapshot.getString("gaminguserid")!!
第31行是:
class HostActivityScreen : AppCompatActivity(),HostAdapter.OnItemCheckListener {
我的调试屏幕截图(不输入addonsucesslistener):
以上代码均无效,我可以看到已获得str值,但未将其输入到addonsuccesslistener或addoncompletelistener循环中。为什么会发生这种情况。我该如何获取字段值?
答案 0 :(得分:-1)
下面对我有用的代码:
mFirestore.collection("AllUsers").document(str).get().addOnSuccessListener(OnSuccessListener<DocumentSnapshot> {documentSnapshot->
var id: String = ""
var gamingname:String=""
if(documentSnapshot.exists()){
id= documentSnapshot.getString("gaminguserid")!!
gamingname=documentSnapshot.getString("gaminname")!!
}else
{
Toast.makeText(this@HostActivityScreen,"Document does not exist",
Toast.LENGTH_LONG).show()
}
}).addOnFailureListener(OnFailureListener { e->
val error=e.message
Toast.makeText(this@HostActivityScreen,"Error:"+error, Toast.LENGTH_LONG).show()
})