Android Question Find value in Firebase Database

Ivan Aldaz

Member
Licensed User
Longtime User
Hi.

In my Firebase Database I have the structure shown in the picture, and want to know if a nickname is available or is already in use.

upload_2018-9-8_9-43-34.png


After several attempts I think I'm close to the solution with:

B4X:
Dim refNick as DatabaseReference
    refNick.Initialize("refNick", realtime.getReference2("/"), "Verify nickname")
    refNick.orderBykey.equalTo(nickToVerify).setEventname("GetNick", "GetNick").addChildEventListener.addValueEventListener

and then work with the snapshot in "GetNick_onDataChange", but doesn't work.

I've tried also with:

B4X:
refNick.orderByChild("Nickname").equalTo(nickToVerify).setEventname("GetNick", "GetNick").addChildEventListener.addValueEventListener

and

B4X:
refNick.LimitToFirst(1).orderByChild("Nickname").equalTo(nickToVerify).setEventname("GetNick", "GetNick").addChildEventListener.addValueEventListener

...but no luck. Any ideas?

Thank you
 

Ivan Aldaz

Member
Licensed User
Longtime User
Well, at last I found a solution:

B4X:
Dim refNick As DatabaseReference
    refNick.Initialize("refNick", realtime.getReference2("/"), "Verify nickname")
    refNick.addChildEventListener
    refNick.orderByKey

This code generates a "refnick_onChildAdded" event for each record in the database reference ("/" in this case)

Now we work with the snapshot

B4X:
Sub refNick_onChildAdded(Snapshot As Object, child As String, tag As Object)

' "child" is each userID (see image in post #1): C70mv4Aq..., svoVVJ6BBD..., wizObfi7K...
    
    'In "Snapshot" we have all data inside each user record:
    Dim ss As DataSnapshot
        ss.Initialize(Snapshot)

    'Get the value of the field "Nickname":
    Dim nickValue As String = ss.getChild("Nickname").Value
        
        'Compare strings:          newNickToVerify is the global variable that holds the nick to verify :)
        If nickValue.ToLowerCase = newNickToVerify.ToLowerCase Then  'make no sensitive
            '...code
        else
            '...code
        End If

End Sub

I guess there's a more elegant way to do this, but it works and for the moment is enough for me.
 
  • Like
Reactions: ziz
Upvote 0
Top