I am developing an Android app using Cloud Firestore to store data. This is how I set data to the database:
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()
}
}
This works great, but there is one exception. When I want to load data to the Firestore, but there is no connection to the internet, neither the onSuccessListener
nor the onFailureListener gets called. I know that this is because they only get called when the data is written to the Firestore. But I don't know of any other way to check if there is a connection or not. For example, when I want to show a progress dialog until the data is successfully written to the Firestore, it would not dismiss if there was no connection. So how can I check that?