#Region Project Attributes
#ApplicationLabel: FirebaseDB
#VersionCode: 3
#VersionName: rx
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#End Region
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
'#AdditionalJar: com.google.firebase:firebase-core
'
' ║ ***** ***** ***** ***** ***** ***** ***** *****
' ║ Testproject for first steps with the
' ║ Firebase Realtime Database
' ║ ***** ***** ***** ***** ***** ***** ***** *****
' ║
' ║ Info for first time users:
' ║
' ║ 1. Open your App in the Firebase console: https://console.firebase.google.com and select "Database" on the left
' ║ 2. Select the RULES tab and set the rules for your access (e.g. the rules below for test purposes)
' ║ 3. Select the DATA tab to watch the database changes later
' ║ 4. Make sure you have the correct "google-services.json"-file in your B4X project folder
' ║ 5. Make sure you have the correct packagename [Ctl+B] to match with your Firebase settings
' ║ 6. Set your Firebase project id in Activity_Create
' ║ 7. Open the IDE Logs window [F6]
' ║ 8. Compile and Run with [F5]
' ║
' ║
' ║ Just in case you need the rules for easy access (make sure the "true" words are lowercase!)
' // These rules give ANYONE, even people who are not users of your app,
' // read and write access to your database
' {
' "rules": {
' ".read": true,
' ".write": true
' }
' }
' ║
' ║ If you see an errormessage like the one below, then it's propably due to step 6 above:
' main_activity_create (java line: 349)
' com.google.firebase.database.DatabaseException: Invalid URL (....)
' ║
' ║
' ║ --- --- --- ---
' ║ USE ALWAYS @DonManfreds MOST RECENT Wrap of the Firebase-Realtime-Database-Library --> https://www.b4x.com/android/forum/threads/firebase-realtimedatabase.69773/
' ║ --- --- --- ---
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
End Sub
Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
Dim realtime As FirebaseDatabase
Dim ref As DatabaseReference
End Sub
Sub Activity_Create(FirstTime As Boolean)
'Activity.LoadLayout("Layout1")
realtime.Initialize("Realtime")
realtime.PersistenceEnabled = True
realtime.goOnline
' ║
Dim strMyProjectId As String = "yyyymyid" ' <-- At first put YOUR Firebase project id HERE <-- <-- <-- <-- <-- <-- <-- <-- <-- <--
' - correct --> "mytestapp-4c1f8"
' - wrong --> "https://mytestapp-4c1f8"
' - wrong --> "https://mytestapp-4c1f8/"
' ║
Dim strTopNode As String = "testnode1"
ref.Initialize("Reference",realtime.getReferencefromUrl($"https://${strMyProjectId}.firebaseio.com/${strTopNode}/"$) )
ref.addChildEventListener
ref.addListenerForSingleValueEvent
ref.addValueEventListener
''Log("ref testnode1 = " & ref.Child("testnode1"))
End Sub
Sub Activity_Resume
Testfunction_updateChildren
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub Reference_onCancelled(errnum As Int,error As String)
Log($"ref_onCancelled(${errnum},${error})"$)
End Sub
Sub Reference_onChildAdded(snapshot As Object, child As String)
Log($"ref_onChildAdded(${child})"$)
End Sub
Sub Reference_onChildChanged(snapshot As Object, child As String)
Log($"ref_onChildchanged(${child})"$)
End Sub
Sub Reference_onChildMoved(snapshot As Object, child As String)
Log($"ref_onChildMoved(${child})"$)
End Sub
Sub Reference_onChildRemoved(snapshot As Object)
Log($"ref_onChildRemoved()"$)
End Sub
Sub Reference_onDataChange(snapshot As Object)
Log($"ref_onDatachange()"$)
Try
Dim snap As DataSnapshot = snapshot
'Log(" Value="&snap.Value)
Dim x As String = snap.Value
If x.Length > 0 Then
x = x.SubString2(0, Min(32, x.Length -1)) & "..."
End If
Log("#- Value=" & x)
Catch
Log("#- ERROR..." & CRLF & LastException.Message)
End Try
End Sub
Sub Testfunction_updateChildren
Log("#-Testfunction_updateChildren")
'### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
' This is an extract from "Sub writeNewPost(...)" from here: https://www.b4x.com/android/forum/threads/firebase-database-rest-and-realtime-testproject.70156/
'### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
'Sub writeNewPost(strUid As String, strUNam As String, strTitle As String, strBody As String) As Boolean
Dim strUid As String = "-KXY123" ' <-- This is normally defined at the login
Dim strUNam As String = "Mike Testuser" ' <-- Comes from the login
Dim strTitle As String = "This is a testtitle"
Dim strBody As String = "Bodytext-Bodytext-Bodytext."
'### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
Dim userref As DatabaseReference = ref.Child("posts") ' <-- One node we want to write the data to
Dim posts As DatabaseReference = userref.push ' <-- We just need this reference to get the autogenerated KEY
Dim key As String = posts.Key
Log("#- key=" & key)
Dim mapPostValues As Map
mapPostValues.Initialize
mapPostValues.Put("Uid", strUid)
mapPostValues.Put("UNam", strUNam)
mapPostValues.Put("tstamp", DateTime.Now)
mapPostValues.Put("tstamp2", DateTime.Date(DateTime.Now) & ", " & DateTime.Time(DateTime.Now))
mapPostValues.Put("Title", strTitle)
mapPostValues.Put("Body", strBody)
' Fanout the data to different paths ("NoSQL" recommendation for up to 1 million simultanous users) --> https://firebase.googleblog.com/2015/10/client-side-fan-out-for-data-consistency_73.html
Dim strUk1 As String = "/posts/" & key
Dim strUk2 As String = "/user-posts/" & strUid & "/" & key
Log("#- strUk1=" & strUk1)
Log("#- strUk2=" & strUk2)
Dim childUpdates As Map
childUpdates.Initialize
childUpdates.Put(strUk1, mapPostValues)
childUpdates.Put(strUk2, mapPostValues)
ref.updateChildren(childUpdates) ' <-- This is the "atomic" update. One start of transaction no matter how many elements the map has
Log("#- childUpdates=" & childUpdates)
End Sub
Sub Reference_onComplete(errorCode As Int, errorMessage As String, errObj As Object, dbref As Object)
Log($"Reference_onComplete(${errorCode},${errorMessage})"$)
If errObj <> Null Then
Dim err As DatabaseError = errObj
Log($" err.Code =${err.Code}"$)
Log($" err.Details=${err.Details}"$)
Log($" err.Message=${err.Message}"$)
End If
If dbref <> Null Then
Dim ref As DatabaseReference = dbref
Log($" ref.Key=${ref.Key}"$)
End If
End Sub