我的问题非常简单明了。我已经从firestore cloud-firestore数据库中获取了数据,在AutoCompleteTextView中建议它很好,并且可单击。但是,我想获取所选项目的firebase cloud-firestore文档ID。经过烘烤的测试
private var autoComplete: ArrayAdapter<String>? = null
private var itemId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
readData(object: MyCallback {
override fun onCallback(value: ArrayAdapter<String>) {
Log.d(TAG, "The list has: " + value.count.toString() + " items.")
}
})
textCurrentSearch.setAdapter(autoComplete)
textCurrentSearch.onItemClickListener = OnItemClickListener { parent, view, position, id ->
showShortToast(this@NewOrderActivity, "Item on cloud-firestore id: " + itemId!! + "Item on ArrayAdapter id: " + id)
}
}
fun showShortToast(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
private fun readData(myCallback : MyCallback) {
Log.d(TAG, "Before attaching the listener!")
mFirebaseFirestore.collection("tblProductItems").get().addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("TAG", "Inside onComplete function!")
for (document in task.result!!) {
val name = document.data["name"].toString()
itemId = document.id
autoComplete?.add(name)
}
myCallback.onCallback(autoComplete!!)
} else showShortToast(this@NewOrderActivity, task.exception!!.toString())
}.addOnSuccessListener {
showShortToast(this@NewOrderActivity, "")
}
Log.d(TAG, "After attaching the listener!")
}
interface MyCallback {
fun onCallback(value: ArrayAdapter<String>)
}
我尝试过
itemId = suggestSnapshot.id
,但无法获取所选产品项重复项的ID。请提供有益的帮助,谢谢。
答案 0 :(得分:0)
要解决此问题,请移动设置添加适配器的行,并在回调内部附加列表程序,如下所示:
override fun onCreate(savedInstanceState: Bundle?) {
mFirebaseFirestore.collection("tblProductItems").addSnapshotListener { querySnapshot, exception ->
if (exception != null) {
showShortToast(this@NewOrderActivity, exception.toString())
}
for (suggestSnapshot in querySnapshot!!.documents) {
val suggestion = suggestSnapshot.getString("name")
itemId = suggestSnapshot.id
//Add the retrieved string to the list
autoComplete?.add(suggestion)
}
textCurrentSearch.setAdapter(autoComplete)
textCurrentSearch.onItemClickListener = OnItemClickListener { parent, view, position, id ->
showShortToast(this@NewOrderActivity, "Item on cloud-firestore id: " + itemId!! + "Item on ArrayAdapter id: " + id)
}
}
}
Firebase API是异步的,这意味着只有在等待数据时数据才可用。有关更多信息,建议您也从此 post 中查看我的答案。