FirebaseRealtimeDatabase4J

DonManfred

Expert
Licensed User
Longtime User
FirebaseRealtimeDatabase4j
Author:
DonManfred (wrapper)
Version: 1

  • Methods:
    • toString As String
    Properties:
    • Name As String
    • Phone As Long
    • Surname As String
  • DataSnapshot
    Methods:
    • Initialize (snapshot As DataSnapshot)
    • IsInitialized As Boolean
    • Value2Map (value As Object) As Object
    • exists As Boolean
      Returns true if the snapshot
      contains a non-null value.
    • getChild (path As String) As DataSnapshot
      Get a DataSnapshot for the location
      at the specified relative path.
    • hasChild (child As String) As Boolean
      Can be used to determine if this
      DataSnapshot has data at a
      particular location
    • hasChildren As Boolean
    Properties:
    • Children As Iterable [read only]
      Gives access to all of the
      immediate children of this snapshot.
    • ChildrenCount As Long [read only]
    • Key As String [read only]
    • Priority As Object [read only]
      Returns the priority of the data
      contained in this snapshot as a
      native type.
    • Ref As DatabaseReference [read only]
      Used to obtain a reference to
      the source location for this
      snapshot.
    • Value As Object [read only]
  • DatabaseError
    Fields:
    • DATA_STALE As Int
    • DISCONNECTED As Int
    • EXPIRED_TOKEN As Int
    • INVALID_TOKEN As Int
    • MAX_RETRIES As Int
    • NETWORK_ERROR As Int
    • OPERATION_FAILED As Int
    • OVERRIDDEN_BY_SET As Int
    • PERMISSION_DENIED As Int
    • UNAVAILABLE As Int
    • UNKNOWN_ERROR As Int
    • USER_CODE_EXCEPTION As Int
    • WRITE_CANCELED As Int
    Methods:
    • Initialize (error As DatabaseError)
    • IsInitialized As Boolean
    Properties:
    • Code As Int [read only]
      returns One of the defined status codes,
      depending on the error
    • Details As String [read only]
      returns Human-readable details on the
      error and additional information,
      e.g. links to docs;
    • Message As String [read only]
      returns a human-readable description of the error
  • DatabaseReference
    Events:
    • onCancelled (errnum as Int As , error As String, errObj As Object)
    • onChildAdded (snapshot As Object, child As String)
    • onChildChanged (snapshot As Object, child As String)
    • onChildMoved (snapshot As Object, child As String)
    • onChildRemoved (snapshot As Object)
    • onComplete (errorCode As Int, errorMessage As String, errObj As Object, dbRef As Object)
    • onDataChange (snapshot As Object)
    Methods:
    • Child (child As String) As DatabaseReference
      Get a reference to location
      relative to this one
    • Database As FirebaseDatabase
      Gets the Database instance associated
      with this reference.
    • Initialize (EventName As String, reference As DatabaseReference)
    • IsInitialized As Boolean
    • LimitToFirst (count As Int) As Query
    • LimitToLast (count As Int) As Query
    • Parent As DatabaseReference
    • Ref As DatabaseReference
    • Root As DatabaseReference
    • Value2Map (value As Object) As Object
    • addChildEventListener
    • addListenerForSingleValueEvent
    • addValueEventListener
    • goOffline
      Manually disconnect the Firebase Database
      client from the server and disable
      automatic reconnection.
    • goOnline
      Manually reestablish a connection to the
      Firebase Database server and enable
      automatic reconnection.
    • keepSynced (keepSynced As Boolean)
      By calling `keepSynced(true)` on a location, the data for that
      location will automatically be downloaded and kept in sync,
      even when no listeners are attached for that location.
    • newMap As Object
    • orderByChild (child As String) As Query
    • orderByKey As Query
    • orderByPriority As Query
    • orderByValue As Query
    • push As DatabaseReference
      Create a reference to an auto-
      generated child location.
    • removeValue
      Set the value at this location to 'null'
    • setEventName (EventName As String)
    • updateChildren (EventName As String, map As Map)
    Properties:
    • Key As String [read only]
    • Value As Map [write only]
  • FirebaseDatabase
    Methods:
    • Initialize (EventName As String, jsonfile As String, databaseUrl As String)
      Gets the instance of FirebaseDatabase
      for the default FirebaseApp.
    • IsInitialized As Boolean
  • FirebaseDatabase
    Methods:
    • Initialize (EventName As String)
      Gets the instance of FirebaseDatabase
      for the default FirebaseApp.
    • IsInitialized As Boolean
    • Value2Map (value As Object) As Object
    • getReference (path As String) As DatabaseReference
      Gets a DatabaseReference for
      the provided path.
    • getReferencefromUrl (url As String) As DatabaseReference
      Gets a DatabaseReference
      for the provided URL.
    • goOffline
      Shuts down our connection to the Firebase
      Database backend until goOnline() is called.
    • goOnline
      Resumes our connection to the Firebase
      Database backend after a previous
      goOffline() call.
    • orderByValue As Query
    • purgeOutstandingWrites
      The Firebase Database client automatically
      queues writes and sends them to the server
      at the earliest opportunity, depending on
      network connectivity.
    Properties:
    • App As FirebaseApp [read only]
      Returns the FirebaseApp instance to
      which this FirebaseDatabase belongs.
    • LogLevel As Level [write only]
      By default, this is set to INFO.
    • PersistenceEnabled As Boolean [write only]
      The Firebase Database client will cache synchronized
      data and keep track of all writes you've initiated
      while your application is running.
  • Query
    Methods:
    • Initialize (qry As Query)
      The Query class (and its subclass, DatabaseReference) are
      used for reading data. Listeners are attached, and they will
      be triggered when the corresponding data changes.
      Instances of Query are obtained by calling startAt(),
      endAt(), or limit() on a DatabaseReference.
    • IsInitialized As Boolean
    • LimitToFirst (count As Int) As QueryWrapper
      Create a query with limit and anchor
      it to the start of the window
    • LimitToLast (count As Int) As QueryWrapper
      Create a query with limit and anchor it
      to the end of the window
    • endAtBool (value As Boolean, key As String) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as
      default, and additionally only child nodes with a
      key less than or equal to the given key.
    • endAtBool2 (value As Boolean) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as default.
    • endAtDouble (value As Double, key As String) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as
      default, and additionally only child nodes with a
      key less than or equal to the given key.
    • endAtDouble2 (value As Double) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as default.
    • endAtString (value As String, key As String) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as
      default, and additionally only child nodes with a
      key key less than or equal to the given key.
    • endAtString2 (value As String) As QueryWrapper
      Create a query constrained to only return child nodes
      with a value less than or equal to the given value,
      using the given orderBy directive or priority as default.
    • keepSynced (keepSynced As Boolean)
      By calling `keepSynced(true)` on a location, the data for that
      location will automatically be downloaded and kept in sync,
      even when no listeners are attached for that location.
    • orderByChild (child As String) As QueryWrapper
      Create a query in which child nodes are
      ordered by the values of the specified path.
    • orderByKey As QueryWrapper
      Create a query in which child nodes are
      ordered by their keys.
    • orderByPriority As QueryWrapper
      Create a query in which child nodes are
      ordered by their priorities.
    • orderByValue As QueryWrapper
      Create a query in which nodes are
      ordered by their value
    • query As Query

Requirements:
- B4J and two 3rd Party JARs. You can download them HERE. Copy the cotentof the ZIP to your B4J Additional Libs folder. Together with the Library (jar and xml) attached here.

Please note that the lib is NOT tested as yet...
Try it by yourself. Get inspiration of the needed B4J Code while looking at the B4A Library i wrote... The code should be kind of the same.

Have fun and good luck ;-)
 

Attachments

  • FirebaseRealtimeDatabase4J.zip
    17.7 KB · Views: 696
Last edited:

DonManfred

Expert
Licensed User
Longtime User
I was writing this library right now and almost finished it!
Ohh, SORRY!

I wrote it for b4a and after requesting a b4j version i decided to make a clone of my lib to use in b4j. The result is the library here... All i changed was 5 lines of code or so to get it compiled with B4J SLC.
 

jmon

Well-Known Member
Licensed User
Longtime User
Ohh, SORRY!

I wrote it for b4a and after requesting a b4j version i decided to make a clone of my lib to use in b4j. The result is the library here... All i changed was 5 lines of code or so to get it compiled with B4J SLC.
Don't be sorry ! You're saving me lots of time, thank you for sharing :) I'll test your library right now!
 

DonManfred

Expert
Licensed User
Longtime User
Don't be sorry ! You're saving me lots of time, thank you for sharing
You´re welcome!

almost finished it!
Thanks a lot!
I just thought it COULD be kind of "i did it too.. Thank you, now my work are nonsens"
So i thought i was bothering you with my release which was not my intention ;)

Great to hear it is not the case here :)
 

jmon

Well-Known Member
Licensed User
Longtime User
Ok, I get some errors :
error1.PNG

It's searching for the firebase-server sdk file in the internal library folder. Notice that there is a doubled ".jar.jar" in the file name.

It also searches for the json-20160810.jar.jar (with doubled jar.jar (binks?))

After correctly copying my files and renaming them there I get this error:
main._appstart (java line: 53)
java.lang.NoClassDefFoundError: com/google/api/client/json/JsonFactory
at de.donmanfred.FirebaseOptionsBuilderWrapper.Initialize(FirebaseOptionsBuilderWrapper.java:42)
at b4j.example.main._appstart(main.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:93)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:84)
at b4j.example.main.start(main.java:36)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/5951462.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/3711894.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/1575234.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/7816767.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/11714529.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.json.JsonFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 23 more

Am I doing anything wrong?

[edit] Yes it was an honest "Thanks a lot!" :) Also my implementation was using the REST API, so I'm curious to see how your library works.
 

fredo

Well-Known Member
Licensed User
Longtime User
YOU WELCOME.

At this point I would like to come to @DonManfred 's protection. He's one of the busiest member of the B4X community and is giving useful advices whereever he can. Maybe he sometimes gets out of patience or has a bad start in the day (05:15 AM on a Friday).
 

DonManfred

Expert
Licensed User
Longtime User
I'm just asking a question
No need to ask if you do a forum search before :D

you don't have to be so mean!,
snide remarks are not necessary neither useful. ;)

And you post IS useful? PAH!

I just react allergic if i read a unnescessary question where the answer can be EASILY found by a simple forum search.

I dont want to spend my FREE TIME to answer such questions... That´s all!
I did spend my free time to write the lib(s) which you can use it FOR FREE!

Maybe i should change it and release all libs in the future as chargeable. That´s more profitable for me
 

jmon

Well-Known Member
Licensed User
Longtime User
While you guys fight, I fixed the problem ;) (I think...)

I downloaded google-http-client:
https://developers.google.com/api-client-library/java/google-http-java-client/download

Copied
google-http-client-1.21.0.jar
google-http-client-gson-1.21.0.jar
To the libs folder, and to the b4j's external library folder

I added this line to "FirebaseDatabaseWrapper.java":
B4X:
@DependsOn(values={"firebase-server-sdk-3.0.1","json-20160810", "google-http-client-1.21.0", "google-http-client-gson-1.21.0"})

Compiled, and it worked in B4J!

Now you have to teach me how to use it? How do I initialize it?
 

Attachments

  • jFirebaseRealtimeDatabase.zip
    17.7 KB · Views: 539
  • src.zip
    9.7 KB · Views: 451
Last edited:

DonManfred

Expert
Licensed User
Longtime User
wow... As the time being i did not fixed it... I tried a lot of imports... Partially it works but then i get crashes due to incompatible json-parsing...

I´ll try to add your imports...

this is my example-code so far

B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Dim realtime As FirebaseDatabase
    Dim ref As DatabaseReference
    Dim db As Map
    Dim opt As FirebaseOptions

End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
    MainForm.Show
    opt.Initialize("FB",File.Combine(File.DirApp,"credentials.json"),"https://xxxxxx.firebaseio.com/")
    If File.Exists(File.DirApp, "credentials.json") = True Then
    Log(File.Combine(File.DirApp,"credentials.json"))
        realtime.Initialize("Realtime",opt.App)
  Else
    Log("credentials.json not found")
  End If
    realtime.goOnline
    'realtime.getReferencefromUrl("https://xxxxx.firebaseio.com/")
 
    'ref.Initialize("Reference",realtime.getReferencefromUrl("https://tactical-patrol-603.firebaseio.com/"))
    'ref.addChildEventListener
    'ref.addListenerForSingleValueEvent
    'ref.addValueEventListener
    'Log(ref.Key)

End Sub


Sub Reference_onComplete(errorCode As Int, errorMessage As String, errObj As Object)
    Log($"ref_onCancelled(${errorCode},${errorMessage})"$)
    Dim err As DatabaseError = errObj
End Sub
Sub Reference_onCancelled(errnum As Int,error As String, errObj As Object)
    Log($"ref_onCancelled(${errnum},${error})"$)
    Dim err As DatabaseError = errObj
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()"$)
    Dim snap As DataSnapshot = snapshot
    Dim m As Map = snap.Value
    db = m
    If db.IsInitialized Then
        't.Enabled = True
    End If

 
    Log("Map "&db)
End Sub

But.

With your imports it compiles fine (i reached this point too).
but running the sample gives more errors...

Program started.
main._appstart (java line: 56)
java.lang.NoClassDefFoundError: com/google/gson/stream/JsonReader
at com.google.api.client.json.gson.GsonFactory.createJsonParser(GsonFactory.java:86)
at com.google.api.client.json.gson.GsonFactory.createJsonParser(GsonFactory.java:76)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.fromStream(GoogleCredential.java:250)
at com.google.firebase.FirebaseOptions$Builder.setServiceAccount(FirebaseOptions.java:77)
at de.donmanfred.FirebaseOptionsBuilderWrapper.Initialize(FirebaseOptionsBuilderWrapper.java:47)
at b4j.donmanfred.fbauth.main._appstart(main.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:93)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:84)
at b4j.donmanfred.fbauth.main.start(main.java:36)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.google.gson.stream.JsonReader
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 24 more

After adding
B4X:
#AdditionalJar: google-api-client-gson-1.22.0
#AdditionalJar: google-oauth-client-1.22.0
#AdditionalJar: google-api-client-1.22.0
the project compiles fine but raises the error above....
I cant find the "correct" jar´s to import it seems :-(
 

jmon

Well-Known Member
Licensed User
Longtime User
Ok I managed to execute your example with no errors, after adding:
google-api-client-1.21.0.jar
google-api-client-gson-1.21.0.jar
google-oauth-client-1.21.0.jar

to the libs folder of my source.

Now depends on is:
B4X:
@DependsOn(values={"firebase-server-sdk-3.0.1","json-20160810", "google-http-client-1.21.0", "google-http-client-gson-1.21.0", "gson-2.1", "google-api-client-1.21.0", "google-api-client-gson-1.21.0", "google-oauth-client-1.21.0"})

And also changed ShotName in FirebaseOptionsBuilderWrapper.java
B4X:
@ShortName("FirebaseOptions")

I'll test to see if the example works now


[edit]
after a while I got this error:
M:\B4j\Tests\FIREBA~1\v02\Objects\credentials.json
Mon Oct 24 23:35:29 ICT 2016 [ERROR] RunLoop: Uncaught exception in Firebase Database runloop (3.0.0). Please report to [email protected]
java.lang.NoSuchMethodError: org.json.JSONStringer.object()Lorg/json/JSONWriter;
at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:56)
at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:45)
at com.google.firebase.database.util.JsonMapper.serializeJson(JsonMapper.java:25)
at com.google.firebase.database.util.GAuthToken.serializeToString(GAuthToken.java:53)
at com.google.firebase.database.core.JvmAuthTokenProvider$1.onComplete(JvmAuthTokenProvider.java:40)
at com.google.firebase.tasks.OnCompleteCompletionListener$1.run(OnCompleteCompletionListener.java:37)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
[edit] not sure if it's linked, but my Realtime Database Console cannot load my project, it says "There was an error loading your projects"?

[edit] I can't initialize realtime with the options, did you change the code for the FirebaseDatabaseWrapper.java? (too many arguments)
B4X:
realtime.Initialize("Realtime",opt.App)
 
Last edited:
Top