Android Question B4A and firebase database.

Richard Goh

Active Member
Licensed User
Longtime User
Yes. Tested and changed to use latest library.
Thanks Erel.

B4X:
Dim req As HttpJob   
    req.Initialize("myjob", Me)
    req.PutString("https://xxxxx.firebaseio.com/Name.json", JSONstring)

Sub JobDone (Job As HttpJob)
    If Job.Success = True Then
       Log(Job.GetString)                 
    Else
        Log("Error: " & Job.ErrorMessage)       
    End If
    Job.Release
End Sub
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
Firebase Database POST and GET is working, but how to implement the DELETE function according to the curl examples?

I got it now basically working with OkHttpUtils2.

25-07-_2016_20-40-08.jpg

So far I can POST and GET values to/from a given path (see attached example) {see here} ,
but am struggling with transferring the Firebase-Docs curl examples to B4A Subs.


a) Since I'm lacking enough knowledge about the Http mechanisms I need a little brainpush on how to transfer

B4X:
curl -X DELETE \
  'https://docs-examples.firebaseio.com/rest/saving-data/users/alanisawesome.json'
into the OkHttpUtils structure.


Nevermind, found it: https://www.b4x.com/android/forum/threads/curl-syntax-with-basic-auth.55749/#post-350854


b) Also I have no Idea how I should use the URI Parameters (e.g. auth)
B4X:
curl -X POST -d '{"Authenticated POST request"}' \
  'https://docs-examples.firebaseio.com/rest/saving-data/auth-example.json?auth=CREDENTIAL'
with OkHttpUtils.
 
Last edited:
Upvote 0

pedrocam

Member
Licensed User
Longtime User
Firebase Database POST and GET is working, but how to implement the DELETE function according to the curl examples?

I got it now basically working with OkHttpUtils2.

View attachment 46394

So far I can POST and GET values to/from a given path (see attached example),
but am struggling with transferring the Firebase-Docs curl examples to B4A Subs.


a) Since I'm lacking enough knowledge about the Http mechanisms I need a little brainpush on how to transfer

B4X:
curl -X DELETE \
  'https://docs-examples.firebaseio.com/rest/saving-data/users/alanisawesome.json'
into the OkHttpUtils structure.


Nevermind, found it: https://www.b4x.com/android/forum/threads/curl-syntax-with-basic-auth.55749/#post-350854


b) Also I have no Idea how I should use the URI Parameters (e.g. auth)
B4X:
curl -X POST -d '{"Authenticated POST request"}' \
  'https://docs-examples.firebaseio.com/rest/saving-data/auth-example.json?auth=CREDENTIAL'
with OkHttpUtils.


Hey thanks for posting your code!!

I was able to get it to work with my DB. I am however getting random characters whenever i try to post anything with your code. Any idea what this could be? They are always like "-KN6j.." see image attachedCapture.PNG

Im also trying to add auth as well, if I get any luck ill let you know.
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
.... I am however getting random characters whenever i try to post anything with your code. Any idea what this could be? They are always like "-KN6j.." see image attached

Yeah, that got me puzzled also for a while.

It's a Firebase generated ID for POSTs.

If you use PUT then everything will be as expected.

I will update my sample project and post it here in an hour or so....
 
Last edited:
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
Firebase Database REST Testproject

As mentioned above here is my testproject as basis to learn around the FiBaDb-REST methods.

*** Please read the introducing comments in the main module ***

The helper subs are incomplete and are my approach as a novice in the Http field.
If you recognize serious security problems or performance issues please let me know.


EDIT: Testproject_06 removed, see Testproject below
 
Last edited:
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
Firebase Database REST POST with access token working

Since there are a lot of options to authenticate a POST...
...I tried many variations and found this working:

1. Database rules:
B4X:
        // These rules require authentication via token
        {
          "rules": {
            ".read": "auth.token != null",
            ".write": "auth.token != null"
          }
        }

2. Added following Sub to the HttpJob class:
B4X:
Public Sub PostString2(Link As String, Text As String, Parameters() As String) ' WORKING!!!!
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append(Link)
    If Parameters.Length > 0 Then
            sb.Append("?")
    End If
    '   
    Dim su As StringUtils
    For i = 0 To Parameters.Length - 1 Step 2  
        If i > 0 Then sb.Append("&")
        sb.Append(su.EncodeUrl(Parameters(i), "UTF8")).Append("=")
        sb.Append(su.EncodeUrl(Parameters(i + 1), "UTF8"))
    Next
    PostBytes(sb.ToString, Text.GetBytes("UTF8") )
End Sub

3. Modified following Sub in the module fibadbhelp of the example project in post #26
B4X:
Public Sub POST(strPath As String, mapData As Map, strJobTag As String) ' WORKING with authentication over access token
    Dim jsonGen As JSONGenerator
    jsonGen.Initialize(mapData)
    Dim strJsonToSend As String = jsonGen.ToString

    Dim job1 As HttpJob
    job1.Initialize("FiBaDb_write", Me)
    job1.Tag = strJobTag
    job1.PostString2(strFiBaDbRoot & strPath & ".json", strJsonToSend, Array As String("auth", Starter.strFirebaseSignedInUserToken))
    job1.GetRequest.SetContentType("application/json")
End Sub


But be aware. I'm still a novice in working with the Http protocol.

As said above "If you recognize serious security problems or performance issues please let me know."


Unless someone's stopping me I will expand the FiBaDb testproject over the next days, so that all example operations can be executed authenticated per user.
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
There is a newer version of the testproject here

Please note that this example is for the Firebase Database "RESTful" access only.
The Firebase "Realtime" Database has far more advantages and is available as a library here.

Firebase Database REST example project
Attached is a project to get a grip on the Firebase realtime database with following operations:

POST
PUT
DELETE
GET
GET with callback
GET with download as file
PATCH may follow later eventually, since the functionality is already covered by PUT (yes I know this and this)

Please read the instructions at the top of the main module.

Firebase auth is needed to use the examples, since the authentication runs with access tokens.

If you already have a project with a Firebase setup than you easily import the following modules:

testfiba.bas
fibadbhelp.bas

and don't forget to set the needed variables in starter (e.g. "strFirebaseSignedInUserToken")

As said above "If you recognize serious security problems or performance issues please let me know."



Tags: #FIBAS #Firebase #Firebasedatabase
 

Attachments

  • fredo_FiBaDb_tester_09.zip
    22 KB · Views: 440
Last edited:
Upvote 0

KMatle

Expert
Licensed User
Longtime User
As far as I understand the concept of Firebase DB it's all about storing JSON's as simple objects or as a mother/child knots dependencies. Very dynamic.

Does anyone know how they handle it internaly (is there a real db behind it or just a file storage). What about Performance?
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
... What about Performance?

I don't know for sure, but I have the feeling, they store it in some sort of json-files.

But I think this can stay transparent for us, since it is handled by Google's technologies (and from what I heard they know how to do it really fast).

As the Firebase docs says here you should structure your trees in a special way so I assume it is designed to handle millions of concurring users for your app at once.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
They mentioned too that you should keep your structure FLAT... ALL children will be synced to if you do any change(or add/change/remove a child).

I´ll have a look at the test-code to get deeper into the FB-DB as i´m interested on how it works (out of curiosity; i dont need it as yet).

I´m watching the thread with interest :)
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
Good read for FireBase Database NoSql Structure best practices

While doing a research on the best way to denormalize my SQLite databases for high performance i came to this article:

01-08-_2016_19-29-08.jpg

01-08-_2016_19-27-07.jpg




I think this knowledge is essential for working with the Firebase Database, since it differs drastically from what we were used to with e.g. SQLite.

Tags: #FIBAS #Firebase #Firebasedatabase #NoSQL
 
Last edited:
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
... I'm writing the wrapper for the Realtime Database ...

How is it going so far with the wrapping of the Firebase Realtime Database library?

I got the REST approach via OkHttp working (see example project here) and can perform the CRUD methods on the data.
But it is not effective enough for what I need for my next projects.

What is really needed are the key capabilities:
  • Realtime synchronising between all connected devices after data change
  • Offline persitance on the device with synch to the cloud on reconnect
  • Accessibility from mobile devices or WebApps
  • Security rules control (who has what access)
If I would be able to wrap the "com.google.firebase:firebase-database:9.4.0" from the Firebase SDK I would dive into it immediately since the benefit from it "will be Gold".

But by now I depend on you wrap experts
and will be delighted to pay
for a working lib
so I can progress with my project.
 
Upvote 0

fredo

Well-Known Member
Licensed User
Longtime User
...Does anyone know how they handle it internaly (is there a real db behind it or just a file storage). What about Performance?

@KMatle I found this while working through all necessities to build a professional cloudbased app in the Firebase world.

Maybe it has some useful information for you.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
If I would be able to wrap the "com.google.firebase:firebase-database:9.4.0" from the Firebase SDK I would dive into it immediately since the benefit from it "will be Gold".
I´ll capture the thread here to give a impression of the lib i wrapped so far... Basically it is working. Did not made much tests with it for sure...

As of now i dont know how - in b4a - i could work with the result given from the log.

Ok, here we go.

B4X:
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
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    realtime.Initialize("Realtime")
    realtime.PersistenceEnabled = True
    realtime.goOnline

    Dim ref As DatabaseReference
    ref.Initialize("Reference",realtime.getReferencefromUrl("https://tactical-patrol-603.firebaseio.com/"))
    ref.addChildEventListener
    ref.addListenerForSingleValueEvent
    ref.addValueEventListener
End Sub

Sub Activity_Resume
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()"$)
    Dim snap As DataSnapshot = snapshot
    Log("Value="&snap.Value)
    'Dim json As JSONParser
    'json.Initialize(snap.Value)
    'Dim root As Map = json.NextObject
    'Log(root)
    'Dim keys As List = snap.Children
    'Log(keys.Size)
    'Log(snap.Children)
End Sub

** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
ref imagesizes = (DatabaseReference) https://tactical-patrol-603.firebaseio.com
** Activity (main) Resume **
ref_onChildAdded(null)
ref_onChildAdded(boolean)
ref_onChildAdded(imagesizes)
ref_onChildAdded(number)
ref_onDatachange()
Value={ValueINt=8192, imagesizes=[{width=407, height=746, filename=0024.png, ext=png}, {width=338, height=574, filename=0025.png, ext=png}, {width=308, height=674, filename=0026.png, ext=png}, {width=330, height=545, filename=0027.png, ext=png}, {width=176, height=119, filename=100_0113.png, ext=png}, {width=256, height=346, filename=1250.png, ext=png}, {width=1667, height=714, filename=1251.png, ext=png}, {width=269, height=120, filename=2000likes001.png, ext=png}], welcomeMessage=Hello B4X World! :D, TestFlagBool=true}

Please note that i created the database in the console with importing a json file to the database....

Attached you can find a json export from the firebase console...
 

Attachments

  • tactical-patrol-603-export-3.json.txt
    871 bytes · Views: 316
Last edited:
Upvote 0

Eme Fibonacci

Well-Known Member
Licensed User
Longtime User
Please someone help me understand firebase in B4A context?

From firebase page:
Once a user authenticates to your app, Firebase manages their session, ensuring that the user is remembered across browser or application restarts.
but how this works in B4A? How "set", "update" and "push" can be made only to authenticated users if no session here?

Maybe because my English is bad this has been a difficult subject to understand for me.

If you can write an explanation...

I thank you very much .
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
As far as I understand it the library at present will give you a databasereference for the App you created in your firebaseconsole and from which you downloaded the jsonfile...
In fact the database for your app as defined in FBconsole.

As i understand! I may be wrong :)
 
Upvote 0

Daniel-White

Active Member
Licensed User
Longtime User
Firebase Database REST example project
Attached is a project to get a grip on the Firebase realtime database with following operations:
POST
PUT
DELETE
GET
GET with callback
GET with download as file
PATCH may follow later eventually, since the functionality is already covered by PUT (yes I know this and this)

Please read the instructions at the top of the main module.

Firebase auth is needed to use the examples, since the authentication runs with access tokens.

If you already have a project with a Firebase setup than you easily import the following modules:
testfiba.bas
fibadbhelp.bas

and don't forget to set the needed variables in starter (e.g. "strFirebaseSignedInUserToken")​

As said above "If you recognize serious security problems or performance issues please let me know."
Hi Fredo, one very simple question.

I filled out the fields : strFirebaseProjectId and strFirebaseDbSecret
but I am a little confuse with the rest in FrireBaseAuth, I need to fill out too? where can I find the strFirebaseSignedInUserToken ? I did not see it in FireBase Console.
Thanks you


Sub Process_Globals
Dim strFirebaseProjectId As String = "blablabla-myproject-7a71c"
Dim strFirebaseDbSecret As String = "3V8nqsdsdsdsdsdJUc1ktbeKr1nHlrftUwtrOfj" ' #wtd Save encryptet in KVS later!!!

Public auth As FirebaseAuth
Dim strFirebaseSignedInUserToken As String = ""
Dim strFirebaseSignedInUser As String = ""
Dim strFirebaseSignedInUserEMail As String = ""
Dim strFirebaseSignedInUserPictureUrl As String= ""
 
Upvote 0
Top