Android Code Snippet FireStore StructuredQuery API REST

HI everyone!
I share with you this code that allows you to make a query in a firestore database applying filters by fields
It is complemented with this publication by Paolo https://www.b4x.com/android/forum/threads/firestore-api-rest-support.129551/
This is the link to the firestore documentation https://cloud.google.com/firestore/docs/reference/rest/v1beta1/StructuredQuery#Projection




query:
sub Class_Globals
    Private user As FirebaseAuth
    Public tokenIdServer as String
    Private projectId As String = "XXXXXXXXXXXXX" ' Id FirebaseProject
 End sub

Public Sub Initialize
    user.Initialize("user")
End Sub

Sub token  '  to execute a query you must request a token. You can call this sub in your code wherever you need it
        user.GetUserTokenId(user.CurrentUser,False) ' The response raises Sub user_TokenAvailable
End Sub


Sub user_TokenAvailable (User As FirebaseUser, Success As Boolean, TokenId As String)
    tokenIdServer= TokenId   '--> token to use in Sub query
    code   ' when you get the token to perform the query, you call the sub code
End Sub


   sub code
'create the structure to perform a filter query
   Dim mapa As Map
    mapa.Initialize
 
    Dim data As List
    data.Initialize
    data.Add(CreateMap("collectionId":"test"))   'test-> collection Firestore
 
    Dim mapafiltro As Map
    mapafiltro.Initialize
    mapafiltro.Put("field",CreateMap("fieldPath":"name"))  ' name field
    mapafiltro.Put("op","EQUAL")
    mapafiltro.Put("value",CreateMap("stringValue":"gregorio"))   'gregorio = value
    mapa.Put("from",data)
    mapa.Put("where",CreateMap("fieldFilter":mapafiltro))
 
    query (mapa)
end sub
 



Public Sub query(runquery As Map) As ResumableSub
 Try
        Dim url As String = $"https://firestore.googleapis.com/v1/projects/${projectId}/databases/(default)/documents:runQuery"$
        Dim json As JSONGenerator
        json.Initialize(CreateMap("structuredQuery": runquery))
            Dim j As HttpJob : j.Initialize("",Me)
            Log(json.ToString)
            j.PostString(url,json.ToString)
            j.GetRequest.SetHeader("Authorization","Bearer " & tokenIdServer)
            j.GetRequest.SetContentType("application/json")  
            Wait For (j) JobDone(j As HttpJob)
            Return GenerateResultquery(j)
        Catch
        Log(LastException)
    End Try
End Sub
Private Sub GenerateResultquery(j As HttpJob) As String
    Try
    Dim response As String = ""
    If j.Success Then
        response = j.GetString
        Log(j.GetString)
    Else
        response = j.ErrorMessage
    End If
 
    j.Release
        Return response

    Catch
        Log(LastException)
        End Try
End Sub



regards
 
Last edited:

Reinierus

Member
Licensed User
Longtime User
Saludos Gregorio.
Estoy tratando de seguir tu ejemplo para implementarlo en un proyecto que estoy realizando, pero no se cuales librerías se requiere agregar al proyecto. Es por ello que ésta línea me da error:
Private user As FirebaseAuth

Además no veo donde se declara esta variable:
tokenIdServer '--> token to use in Sub query

Por favor su ayuda.

Muchas gracias,
 

Mashiane

Expert
Licensed User
Longtime User
If you don't mind me adding, in case anyone would want something similar to execute queries against Firebase using SQL statements for Web using JavaScipt, I found this useful library, https://firebaseopensource.com/projects/jsayol/firesql/

I guess it would be pretty awesome if one could just write SQL statements for it even for these android/ios use cases.

#MyTwoCents.
 

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hello, sorry, first you need to integrate the application with Firebase following this tutorial https://www.b4x.com/android/forum/threads/firebaseauth-authenticate-your-users.67875/
you must use the library FirebaseAuth is an internal library
tokenIdserver is declared in sub Class_Globals, I modify the first post.
 
Last edited:

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hi, everyone!
I add the option to execute a query with multiple filters
In this example I filter by the field name and country

CompositeFilter:
sub code
'OPTIONAL CompositeFilter

                Dim mapafiltro As Map
                mapafiltro.Initialize
                mapafiltro.Put("field",CreateMap("fieldPath":"name"))
                mapafiltro.Put("op","EQUAL")
                mapafiltro.Put("value",CreateMap("stringValue":"Gregorio"))
                mapa.Put("from",datamap)

                Dim lista As List
                lista.Initialize
                lista.Add(CreateMap("fieldFilter":mapafiltro))
               
                Dim mapafiltro As Map
                mapafiltro.Initialize
                mapafiltro.Put("field",CreateMap("fieldPath":"country"))
                mapafiltro.Put("op","EQUAL")
                mapafiltro.Put("value",CreateMap("stringValue":"Argentina"))
                lista.Add(CreateMap("fieldFilter":mapafiltro))
                               
                Dim compositeFilter As Map
                compositeFilter.Initialize
                compositeFilter.Put("op","AND")
                compositeFilter.Put("filters",lista)              
                mapa.Put("where",CreateMap("compositeFilter":compositeFilter))

 
    query (mapa)
end sub


regards
 

Reinierus

Member
Licensed User
Longtime User
Hello Gregorio.
When I follow the tutorial of https://www.b4x.com/android/forum/threads/firebaseauth-authenticate-your-users.67875/ I get this error:

But I put the library into the internal libraries:


There is a missing library?

I note that tutorial is for B4A but I using B4J, so there is not manifest file. It works only in B4A?

Thanks
 

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User


Hi, I don't know B4J enough to answer you, but I don't think so, I use it in B4A. Regards
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…