Android Tutorial Firebase Realtimedatabase get a chat or content preview (filtering)

Hello,

a another Tutorial in the category how to program a nice chat app.
This Tutorial builds on this.

The Realtimedatabase lib. supports filtering, with this feature you can filter your content output, DonManfred has already published a small code snippet about it.

this filters are available [source]:
B4X:
limitToFirst() 'Sets the maximum number of items to return from the beginning of the ordered list of results.
limitToLast() 'Sets the maximum number of items to return from the end of the ordered list of results.
startAt() 'Return items greater than or equal to the specified key or value depending on the order-by method chosen.
endAt() 'Return items less than or equal to the specified key or value depending on the order-by method chosen.
equalTo() 'Return items equal to the specified key or value depending on the order-by method chosen.

This is a screenshoot of the result of this tutorial in my app. (my baby)

Screenshot_20171114-104414.png

"Test 15" , "Test 1" and "Hoho" are the result from the Realtimedatabase and with the time on right.

Lets start with the code.

We need the Firebase Realtimedatabase

i use the AuthEx lib for anonymous login.

B4X:
Sub Process_Globals
'it is better to add this in a Service
Public auth As FirebaseAuthEx
Public realtime As FirebaseDatabase
End Sub

Sub Globals

Dim getLastmsg As DatabaseReference

End Sub

Sub Activity_Create(FirstTime As Boolean)

'this is better in a service! auth.Initialize("auth")
realtime.Initialize("Realtime")
realtime.PersistenceEnabled = True

auth.signInAnonymously

getLastmsg.Initialize("lastmsg",realtime.getReference2("/rooms/" & "idOfTheRoom" & "/messages"),"idOfTheRoom")
        getLastmsg.LimitToLast(1).addChildEventListener 'LimitToLast returns the list from new to old with limit, in this case we want only the last, that's why we set it to "1".
     
        getLastmsg.keepSynced(True)

End Sub


Sub lastmsg_onChildAdded(Snapshot As Object, child As String, tag As Object)
 
    Dim snap As DataSnapshot = Snapshot
    Dim NewMessage As Map = snap.Value
 
    Main.SQL1.ExecNonQuery2("UPDATE chats SET lastmsg = ?, lastmsgtime = ? WHERE sessionid= ? ", Array As Object(NewMessage.Get("text"), NewMessage.Get("timestamp"),tag)) 'this is only a example how to store you the value to the local db, i use the SQLite.
     
        ulv_chats.RefreshContent 'for example refresh the list, to build the list new, with the new values, i use the Ultimate Listview from Informatix.
 
End Sub

Thats all, this is very easy with this lib.

I hope i can help you with this tutorial, it is a nice feature. For tips or questions I'm open.
 
Last edited:
Top