我正在尝试从Firestore获取文档内容。以下图像链接显示了数据库结构Firestore database structure
我想要的内容:我想通过自定义对象获取文档内容并将其添加到列表中。
问题:我收到此错误: E / Android运行时:致命异常:主要 流程:com.example.aalmesbah.turoodpilot,PID:12160 java.lang.RuntimeException:无法反序列化对象。 com.google.firebase.auth.UserInfo类未定义无参数构造函数。如果您使用的是ProGuard,请确保未剥离这些构造函数
我尝试通过 get()和getString()方法获取文档内容,但效果很好,问题仅在于 toObject()吗?
我在这里搜索并尝试了其他问题的一些建议解决方案,例如为数据类添加默认值,但不幸的是,它没有用。
数据类代码:
data class UserInfo (val name: String? = "",
val email: String? = "",
val phoneNum: String? = "",
val address: String? = "") {
constructor(): this("","","", "" )
}
配置文件片段代码:(此处应显示文档内容)
class ProfileFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private lateinit var db: FirebaseFirestore
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_profile, container, false)
auth = FirebaseAuth.getInstance()
db = FirebaseFirestore.getInstance()
return view
}
override fun onStart() {
super.onStart()
val userID = auth.currentUser?.uid
val docRef = db.collection("users").document(userID!!)
docRef.addSnapshotListener(EventListener<DocumentSnapshot> { documentSnapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@EventListener
}
if (documentSnapshot != null && documentSnapshot.exists()) {
docRef.get().addOnSuccessListener { documentSnapshot ->
val userInfo = documentSnapshot.toObject(UserInfo::class.java)
emailTV.text = userInfo?.email
}
} else {
Log.d(TAG, "Current data: null")
}
})
}
}
在注册活动中sendUserData()方法代码
private fun sendUserData() {
val name = userN.text.toString()
val email = userEm.text.toString()
val phone = userPhone.text.toString()
val addressName = addressName.text.toString()
val area = area.text.toString()
val block = block.text.toString()
val street = strees.text.toString()
val avenue = avenue.text.toString()
val house = house.text.toString()
val floor = floor.text.toString()
val apartment = apartment.text.toString()
val additionalInfo = additional.text.toString()
val address = "Addres Name: $addressName \n Area: $area \n B: $block ST: $street Av: $avenue H: $house\n " +
"Floor: $floor Apartment: $apartment \n Notes: $additionalInfo"
val userID = auth.currentUser?.uid
val userData = UserInfo(name, email, phone, address)
db.collection("users").document(userID!!).set(userData).addOnSuccessListener {
Toast.makeText(this, "Successfully Registered", Toast.LENGTH_SHORT).show()
}.addOnFailureListener{
Toast.makeText(this, "Data Upload error!", Toast.LENGTH_SHORT).show()
}
}
答案 0 :(得分:0)
如果您想将Kotlin数据类与documentSnapshot.toObject
一起使用,则必须将每个字段设为可为空的var
而不是val
。 Firestore SDK不知道如何将文档字段映射到数据类构造函数参数中。
如果您想使用val
字段作为适当的不可变数据类,则必须手动从文档中读取每个字段,然后自己调用数据类构造函数。