我正在使用Cloud Firestore开发一个Android应用程序来存储数据。以下是我如何将数据设置到数据库中:
private fun setData() {
val task = UploadDataTask()
task.setOnUploadFinishedListener(object: UploadDataTask.OnUploadFinishedListener{
override fun uploadFinished() {
// Do something
}
override fun uploadFailed() {
// Do something
}
})
}
private class UploadDataTask: AsyncTask<Void, Void, Void>() {
private var onUploadFinishedListener: OnUploadFinishedListener? = null
fun setOnUploadFinishedListener(listener: OnUploadFinishedListener) {
onUploadFinishedListener = listener
}
override fun doInBackground(vararg params: Void?): Void? {
val map = hashMapOf(
UID to firebaseUser.uid
)
firebaseFirestore.collection(USERS)
.document(firebaseUser.uid)
.set(map)
.addOnSuccessListener {
if(onUploadFinishedListener != null)
onUploadFinishedListener!!.uploadFinished()
}
.addOnFailureListener {
if(onUploadFinishedListener != null)
onUploadFinishedListener!!.uploadFailed()
}
return null
}
interface OnUploadFinishedListener {
fun uploadFinished()
fun uploadFailed()
}
}
这个很好用,但是有一个例外。当我想将数据加载到Firestore中时,如果没有连接到因特网,既不会调用
onSuccessListener
也不会调用onFailureListener
。我知道这是因为它们只会在数据写入Firestore时被调用。但我不知道任何其他检查是否连接的方法。例如,当我想显示进度对话框直到数据成功写入Firestore时,如果没有连接,它将不会消失。那么我该如何检查呢?
onSuccess()
不会被调用。 - AprionSuccess()
被触发时,ProgressDialog
将会在您重新连接到互联网后消失。这不正是您想要的吗? - Alex MamoonSuccess()
或onFailure()
时将其关闭,但如果没有网络连接,我也希望将其关闭,然后显示一条消息或其他内容来通知用户上传数据失败。 - AprionSuccess()
和onFailure()
中调用dismiss()
方法。但是如果没有网络连接时关闭对话框,那么当重新连接上时你就无法关闭对话框了,因为对话框已经关闭了。如果你想知道设备是否连接到互联网,请查看在Android上检测是否有互联网连接。现在可以了吗? - Alex Mamo