1

Below is my code to get the result from the barcode scanner, then verify if it is a legit referral code that exist within the Firebase database. If so, the scanner should then display a message to tell the user that they have successfully connected and output the name of the owner of the referral code. However, the listener is somehow not executing, therefore the result is just a blank alert dialog with the "Result" title.

var barcodeLauncher = registerForActivityResult(
        ScanContract()
    ) { result: ScanIntentResult ->
        if (result.contents != null) {
            val builder =
                AlertDialog.Builder(this@ReferralActivity)

            val ref = FirebaseDatabase.getInstance().getReference("Users")

            builder.setTitle("Result")
            var name = ""

            ref.addListenerForSingleValueEvent(object:ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    var exists = false
                    for (postSnapshot in snapshot.children) {
                        var refcode = "${postSnapshot.child("referralCode").value}"
                        if (refcode == result.contents) {
                            name = "${snapshot.child("name").value}"
                            exists = true
                            break
                        }
                    }

                    if (exists) {
                        builder.setMessage("You've successfully connected with $name, enjoy your rewards!")
                    } else {
                        builder.setMessage("No user with such referral code is found...")
                    }
                }

                override fun onCancelled(error: DatabaseError) {
                    builder.setMessage("No user with such referral code is found...")
                }
            })

            builder.setPositiveButton(
                "OK"
            ) { dialogInterface, i -> dialogInterface.dismiss() }.show()
        }
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
YUNG FOOK YONG
  • 109
  • 1
  • 11
  • Are you saying that neither the `onDataChange` nor the `onCancelled` of your `addListenerForSingleValueEvent` is getting called? If so, do you have any other code in your app that accesses (read *or* write) the database that *does* work? – Frank van Puffelen Mar 21 '23 at 13:50
  • @FrankvanPuffelen I believe both are ignored, since the builder does not output anything included in onDataChanged and onCancelled, the output is a blank alert dialog box only with the title. I do have other code which includes login/register that are done using functions that are prepared by Firebase. – YUNG FOOK YONG Mar 21 '23 at 13:52
  • What is the location of your database? – Alex Mamo Mar 21 '23 at 14:14
  • I was asking specifically about code that access the database. Do you have any other code in your app that accesses (read or write) **the database** that does work? If not, it might be that you don't have the right configuration for your database. See my answer here for the options in that case: https://stackoverflow.com/questions/68173632/google-firebase-real-time-database-not-working-as-everything-is-set-correctly/68179677#68179677 – Frank van Puffelen Mar 21 '23 at 15:50
  • @FrankvanPuffelen I do, actually there are code right on top of this section of the code that is similar and able to access the database. – YUNG FOOK YONG Mar 22 '23 at 05:31
  • Hmmm... in that case it seems the configuration of your database URL is correct, and I don't see why neither `onDataChange` nor `onCancelled` gets called for this listener. I hope somebody else spots it. – Frank van Puffelen Mar 22 '23 at 13:38
  • @FrankvanPuffelen I've managed to solve the problem by moving the whole element of the alert dialog builder into the OnDataChange() method, thanks a lot for your time and help. – YUNG FOOK YONG Mar 23 '23 at 01:54
  • Ah, that makes sense. I didn't see the `.show()` call in there, but indeed that would explain. Good to hear you got it working @YUNGFOOKYONG! – Frank van Puffelen Mar 23 '23 at 03:35

1 Answers1

1

I've managed to solve the problem by moving the whole element of the alert dialog builder into the OnDataChange() method.

var barcodeLauncher = registerForActivityResult(
        ScanContract()
    ) { result: ScanIntentResult ->
        if (result.contents != null) {
            var name = ""
            var exists = false

            val ref = FirebaseDatabase.getInstance().getReference("Users")
            ref.addValueEventListener(object:ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    val builder =
                        AlertDialog.Builder(this@ReferralActivity)

                    builder.setTitle("Result")
                    for (postSnapshot in snapshot.children) {
                        if ("${postSnapshot.child("referralCode").value}" == result.contents) {
                            builder.setMessage("You've successfully connected with ${postSnapshot.child("name").value}, enjoy your rewards!")
                            builder.setPositiveButton(
                                "OK"
                            ) { dialogInterface, i -> dialogInterface.dismiss() }.show()
                            return
                        }
                    }
                    builder.setMessage("No account with such referral code found... ")
                    builder.setPositiveButton(
                        "OK"
                    ) { dialogInterface, i -> dialogInterface.dismiss() }.show()
                }

                override fun onCancelled(error: DatabaseError) {

                }
            })


        }
    }
YUNG FOOK YONG
  • 109
  • 1
  • 11