0

I have this piece of code and it is executed with .continueWith and addOnSuccessListener even if failed.I try with continueWithTask but i dont understand very well Tasks API. Please help me to understand how to do this.

db.collection(customGameName).document().get().continueWith {
    if (!gameslist.contains(customGameName)) {
        gameslist.add(customGameName)
        SavedPreference.setGamesList(this, gameslist)
        adapter.notifyDataSetChanged()
    }else{
        Toast.makeText(this,"$customGameName is in the list already!",Toast.LENGTH_SHORT).show()
    }
}.addOnFailureListener {
    Toast.makeText(this,"$customGameName not exist!",Toast.LENGTH_SHORT).show()
    gameslist.remove(customGameName)
    SavedPreference.setGamesList(this, gameslist)
    adapter.notifyDataSetChanged()
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
endy aris
  • 13
  • 3
  • Tell us what is wrong with shared code. Do you have any errors? – Alex Mamo Jun 20 '22 at 07:37
  • I want to run the "if" only if success. This code adds customGameName in the gameslist even if the get failed. I changed continueWith with addOnSuccessListener with the same results. – endy aris Jun 20 '22 at 09:13

1 Answers1

0

If you have code that you only want to run when the task is successful, add a success listener to the task. That should look something like this:

db.collection(customGameName).document().get()
.addOnSuccessListener { document ->
    if (document != null) {
        Log.d(TAG, "DocumentSnapshot data: ${document.data}")
        if (!gameslist.contains(customGameName)) {
            gameslist.add(customGameName)
            SavedPreference.setGamesList(this, gameslist)
            adapter.notifyDataSetChanged()
        }else{
            Toast.makeText(this,"$customGameName is in the list already!",Toast.LENGTH_SHORT).show()
        }
    } else {
        Log.d(TAG, "No such document")
    }
}.addOnFailureListener {
    Toast.makeText(this,"$customGameName not exist!",Toast.LENGTH_SHORT).show()
    gameslist.remove(customGameName)
    SavedPreference.setGamesList(this, gameslist)
    adapter.notifyDataSetChanged()
}

Note that this code is pretty much straight from the Firebase documentation on getting a document in Kotlin, so I recommend spending some more time there.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807