Reputation: 1515
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?
Upvotes: 5
Views: 1940
Reputation: 138824
First thing first. The Cloud Firestore client already runs all network operations in a background thread. This means that all operations take place without blocking the main thread. Putting it in an AsyncTask
does not give any additional benefits.
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.
Simply by displaying the ProgressDialog
once you call setData()
method and dismiss it in onSuccess()
. Since this method is called only when the data is successfully written on Firebase servers, that's the right place to use it.
Furthermore, if you want to have the same behaviour when you read data then you should use isFromCache()
method like explained in my answer from the following post:
Upvotes: 2