B4J Question [ABMaterial] How to reload a page from code.

Rob White

Member
Licensed User
Hi All,

This thread (2016) describes using
B4X:
ABMShared.NavigateToPage(ws, "./")
Two questions:-

1] ABMShared.NavigateToPage has 3 arguments. The above has two. Can I assume that the third argument has been added since 2016?

2] Where do I place the above line in my code?
 

MichalK73

Well-Known Member
Licensed User
Longtime User
ad1.
So now there are 3 parameters. The third means whether the page is to be run in the same tab or in a new one.
ad2.
I don't know why you need to put this line?
Page.Refresh does the trick.
 
Upvote 0

Rob White

Member
Licensed User
Where is the page refresh placed? When I put this at the bottom of BuildPage
B4X:
    If page.IsInitialized Then
        Log("EOF BuildPage")
        page.Refresh
    End If
I get a null pointer exception :-
EOF BuildPage
Error occurred on line: 201 (SelectPaddockPage)
java.lang.NullPointerException
at com.ab.abmaterial.ABMPage.Refresh(Unknown Source)
at com.ab.template.selectpaddockpage._buildpage(selectpaddockpage.java:132)
at com.ab.template.selectpaddockpage._initialize(selectpaddockpage.java:60)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:632)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:234)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:167)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:91)
at anywheresoftware.b4a.shell.ShellBA.raiseEvent2(ShellBA.java:98)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:78)
at com.ab.template.main.main(main.java:29)
I thought there would be no problem.

There are page refresh's in ConnectPage but this is not called a second time. Hence my question where to put some code to refresh the page.
 
Upvote 0

Rob White

Member
Licensed User
I do have initialize.
Here is the page code complete
B4X:
'Class module
Sub Class_Globals
    Private ws As WebSocket 'ignore
    ' will hold our page information
    Public page As ABMPage
    ' page theme
    Private theme As ABMTheme
    ' to access the constants
    Private ABM As ABMaterial 'ignore   
    ' name of the page, must be the same as the class name (case sensitive!)
    Public Name As String = "SelectPaddockPage"  '<-------------------------------------------------------- IMPORTANT
    ' will hold the unique browsers window id
    Private ABMPageId As String = ""
    ' your own variables
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    ' build the local structure IMPORTANT!
    BuildPage
    If page.IsInitialized Then
        Log("At SelectPaddockPage.Initialize")
        page.Refresh
    End If

End Sub

#Region ABM
Private Sub WebSocket_Connected (WebSocket1 As WebSocket)   
    Log("Connected")
        
    ws = WebSocket1       
    
    ABMPageId = ABM.GetPageID(page, Name,ws)
    
    Dim session As HttpSession = ABM.GetSession(ws, ABMShared.SessionMaxInactiveIntervalSeconds)
    If session.IsNew Then
        session.Invalidate
        ABMShared.NavigateToPage(ws, "", "./")
        Return
    End If
        
    If ABMShared.NeedsAuthorization Then
        If session.GetAttribute2("IsAuthorized", "") = "" Then
            ABMShared.NavigateToPage(ws, ABMPageId, "../")
            Return
        End If
    End If       
    ABM.UpdateFromCache(Me, ABMShared.CachedPages, ABMPageId, ws)       
    If page.ComesFromPageCache Then
        ' when we have a page that is cached it doesn't matter if it comes or not from a new connection we serve the cached version.
        Log("Comes from cache")       
        page.Refresh       
        page.FinishedLoading       
    Else
        If page.WebsocketReconnected Then
            Log("Websocket reconnected")
            ' when we have a client that doesn't have the page in cache and it's websocket reconnected and also it's session is new - basically when the client had internet problems and it's session (and also cache) expired before he reconnected so the user has content in the browser but we don't have any on the server. So we need to reload the page.
            ' when a client that doesn't have the page in cache and it's websocket reconnected but it's session is not new - when the client had internet problems and when he reconnected it's session was valid but he had no cache for this page we need to reload the page as the user browser has content, reconnected but we have no content in cache
            ABMShared.NavigateToPage (ws, ABMPageId, "./" & page.PageHTMLName)
        Else
            ' when the client did not reconnected it doesn't matter if the session was new or not because this is the websockets first connection so no dynamic content in the browser ... we are going to serve the dynamic content...
            Log("Websocket first connection")
            page.Prepare
            ConnectPage           
        End If
    End If
    Log(ABMPageId)       
End Sub

Private Sub WebSocket_Disconnected
    Log("Disconnected")
End Sub

Sub Page_ParseEvent(Params As Map)
    Dim eventName As String = Params.Get("eventname")
    Dim eventParams() As String = Regex.Split(",",Params.Get("eventparams"))

    #If DEBUG
    Log($"Evt fired --->${eventName} Number params = ${Params.Size}"$)
    For i = 0 To Params.Size-1
        Log($"    Key = ${Params.GetKeyAt(i)}, value = ${Params.GetValueAt(i)}"$)
    Next
    Log("-----------------------------------------------------")
    #End if
    
    If eventName = "beforeunload" Then
        Log("preparing for url refresh")
        ABM.RemoveMeFromCache(ABMShared.CachedPages, ABMPageId)
        Return
    End If
    Dim caller As Object = page.GetEventHandler(Me, eventName)
    If caller = Me Then
        If SubExists(Me, eventName) Then
            Params.Remove("eventname")
            Params.Remove("eventparams")
            If eventName = "page_dropped" Then
                page.ProcessDroppedEvent(Params)
            End If
            Select Case Params.Size
                Case 0
                    CallSub(Me, eventName)
                Case 1
                    CallSub2(Me, eventName, Params.Get(eventParams(0)))
                Case 2
                    If Params.get(eventParams(0)) = "abmistable" Then
                        Dim PassedTables As List = ABM.ProcessTablesFromTargetName(Params.get(eventParams(1)))
                        CallSub2(Me, eventName, PassedTables)
                    Else
                        CallSub3(Me, eventName, Params.Get(eventParams(0)), Params.Get(eventParams(1)))
                    End If
                Case Else
                    ' cannot be called directly, to many param
                    CallSub2(Me, eventName, Params)
            End Select
        End If
    Else
        CallSubDelayed2(caller, "ParseEvent", Params) 'ignore
    End If
    
End Sub

public Sub BuildTheme()
    ' start with the base theme defined in ABMShared
    theme.Initialize("pagetheme")
    theme.AddABMTheme(ABMShared.MyTheme)

    ' add your specific page themes
    theme.AddInputTheme("Inp")
    theme.Input("Inp").DisabledForeColor=ABM.COLOR_BLUEGREY
    
End Sub

public Sub BuildPage()
    ' initialize the theme
    BuildTheme
    
    ' initialize this page using our theme
    page.InitializeWithTheme(Name, "/ws/" & ABMShared.AppName & "/" & Name, False, ABMShared.SessionMaxInactiveIntervalSeconds, theme)
    page.ShowLoader=True
    page.PageHTMLName = "index.html"
    page.PageTitle = "Select paddock"
    page.PageDescription = "Select paddock(s) to record/edit data"
    page.PageKeywords = ""
    page.PageSiteMapPriority = ""
    page.PageSiteMapFrequency = ABM.SITEMAP_FREQ_YEARLY
    page.ShowGridInfo = False
    page.ShowConnectedIndicator = True
    Dim NuClient As ABMModalSheet'Ignore        - Initialised in the sub
    NuClient = msNuClient.BuildModalNuClient(page)
    
    ' create the page grid
#Region NOT SAVED: 2021-07-04T07:11:37
    'PHONE
    '╔═══════════════════════════════════════════════════════════════════════════════════╗
    '║ 1,1                                                   |                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════╣
    '║ 2,1                       | 2,2                       |                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════╣
    '║ 3,1                       | 3,2                       |                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════╣
    '║ 4,1                       | 4,2                       |                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════╣
    '║ 5,1                       | 5,2                       |                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════╣
    '║ 6,1         |      | 6,2         |      | 6,3         |                           ║
    '╚═══════════════════════════════════════════════════════════════════════════════════╝

    'TABLET
    '╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════╗
    '║ 1,1                                                                   |                                   ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 2,1                               | 2,2                               |                                   ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 3,1                               | 3,2                               |                                   ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 4,1                               | 4,2                               |                                   ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 5,1                               | 5,2                               |                                   ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 6,1             |        | 6,2             |        | 6,3             |                                   ║
    '╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════╝

    'DESKTOP
    '╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
    '║ 1,1                                                                                   |                                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 2,1                                       | 2,2                                       |                                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 3,1                                       | 3,2                                       |                                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 4,1                                       | 4,2                                       |                                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 5,1                                       | 5,2                                       |                                           ║
    '╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
    '║ 6,1                 |          | 6,2                 |          | 6,3                 |                                           ║
    '╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝

    page.AddRows(1,True,"").AddCellsOS(1,0,0,0,8,8,8,"")
    page.AddRows(3,True,"").AddCellsOS(2,0,0,0,4,4,4,"")
    page.AddRows(1,True,"").AddCellsOS(1,0,0,0,2,2,2,"").AddCellsOS(2,1,1,1,2,2,2,"")
    page.BuildGrid ' IMPORTANT!
#End Region
    
End Sub

Sub nuclibut_clicked(target As String)
    Act.Nu = "Client"
    page.ShowModalSheet("NuClientMS")
End Sub

Sub canbut_clicked(target As String)
    page.CloseModalSheet("NuClientMS")
    'ABMShared.NavigateToPage(ws,"HomePage","../HomePage/")
End Sub

Sub createnuclient_clicked(Target As String)
    Log("Create client button on modal form clicked")
    If msNuClient.Savenu(page.ModalSheet("NuClientMS")) = False Then
        Act.SendMess(Act.ErrMess,"NO data saved ")
        page.ShowToast("Tost","mytheme","NO DATA SAVED - "&Act.ErrMess,5000,False)
    End If
    page.CloseModalSheet("NuClientMS")
    Dim cbx As ABMCombo = page.Component("PadCBX")
    cbx.Visibility = ABM.VISIBILITY_HIDE_ALL
    cbx = page.Component("FarmCBX")
    cbx.Visibility = ABM.VISIBILITY_HIDE_ALL
    cbx = page.Component("ClientCBX")
    cbx.SetActiveItemId(-1)
    Dim but As ABMButton = page.Component("nuPadBut")
    but.Visibility = ABM.VISIBILITY_HIDE_ALL
    but = page.Component("nuFarmBut")
    but.Visibility = ABM.VISIBILITY_HIDE_ALL
    page.Refresh
End Sub

public Sub ConnectPage()
    page.ShowGridInfo=False
    
    page.AddModalSheetTemplate(msNuClient.BuildModalNuClient(page))
    
    Dim Title As ABMLabel
    Title.Initialize(page,"Tit",$"${Act.AbrevName} - ${Act.Name(Act.Index)} select paddock"$,ABM.SIZE_H5,False,"mytheme")
    page.Cell(1,1).AddComponent(Title)
        
    Dim NuClientBut As ABMButton
    NuClientBut.InitializeFloating(page,"nuCliBut","mdi-content-add","")
    page.Cell(2,2).MarginTop="20px"
    page.Cell(2,2).AddComponent(NuClientBut)
    
    Dim ClientCBX As ABMCombo
    ClientCBX.Initialize(page,"ClientCBX","Client",300,"mytheme")
    page.Cell(2,1).AddComponent(ClientCBX)
    ClientCBX.Visibility=ABM.VISIBILITY_ALL
    Act.FillCombo(page,ClientCBX,PD.Clients.SelectedData)

    Dim NuFarmBut As ABMButton
    NuFarmBut.InitializeFloating(page,"nuFarmBut","mdi-content-add","")
    page.Cell(3,2).MarginTop="20px"
    page.Cell(3,2).AddComponent(NuFarmBut)
    NuFarmBut.Visibility = ABM.VISIBILITY_HIDE_ALL
    Dim FarmCBX As ABMCombo
    FarmCBX.Initialize(page,"FarmCBX","Farm",300,"mytheme")
    page.Cell(3,1).AddComponent(FarmCBX)
    FarmCBX.Visibility=ABM.VISIBILITY_HIDE_ALL
    
    Dim NuPadBut As ABMButton
    NuPadBut.InitializeFloating(page,"nuPadBut","mdi-content-add","")
    page.Cell(4,2).MarginTop="20px"
    page.Cell(4,2).AddComponent(NuPadBut)
    NuPadBut.Visibility=ABM.VISIBILITY_HIDE_ALL
    
    Dim PadCBX As ABMCombo
    PadCBX.Initialize(page,"PadCBX","Paddock",300,"mytheme")
    page.Cell(4,1).AddComponent(PadCBX)
    PadCBX.Visibility=ABM.VISIBILITY_HIDE_ALL

    Dim HomeBut As ABMButton
    HomeBut.InitializeRaised(page,"HomeBut","","","Home","mytheme")
    HomeBut.SetBorderEx(Act.ButColor,ABM.INTENSITY_DARKEN1,4,ABM.BORDER_SOLID,"20px")
    page.Cell(5,1).AddComponent(HomeBut)
    HomeBut.Visibility=ABM.VISIBILITY_HIDE_ALL
    
    Dim EdtBut As ABMButton
    EdtBut.InitializeRaised(page,"EdtBut","","","Last","mytheme")
    EdtBut.SetBorderEx(Act.ButColor,ABM.INTENSITY_DARKEN1,4,ABM.BORDER_SOLID,"20px")
    page.Cell(5,2).AddComponent(EdtBut)
    EdtBut.Visibility=ABM.VISIBILITY_HIDE_ALL
        
    Dim NewBut As ABMButton
    NewBut.InitializeRaised(page,"NewBut","","","NEW","mytheme")
    NewBut.SetBorderEx(Act.ButColor,ABM.INTENSITY_DARKEN1,4,ABM.BORDER_SOLID,"20px")
    page.Cell(5,3).AddComponent(NewBut)
    NewBut.Visibility=ABM.VISIBILITY_HIDE_ALL
        
        
    ' refresh the page
    page.Refresh
    
    ' Tell the browser we finished loading
    page.FinishedLoading
    ' restoring the navigation bar position
    'page.RestoreNavigationBarPosition
    Log("At bottom of SelectPage")
End Sub

Sub padcbx_clicked(Target As String)
    Dim idx As Int = Target
    PD.Paddocks.SetCurrIndx(idx)           
    Log($"Current paddock is ${PD.paddocks.GetCurrVal("Name")}, ID = ${PD.paddocks.GetCurrVal("ID")}"$)
    Dim Hb As ABMButton = page.Component("HomeBut")
    Hb.Visibility=ABM.VISIBILITY_ALL
    Dim Edt As ABMButton = page.Component("EdtBut")
    Edt.Visibility=ABM.VISIBILITY_ALL
    Dim Gb As ABMButton = page.Component("NewBut")
    Gb.Visibility=ABM.VISIBILITY_ALL
    Edt.Refresh
    Hb.Refresh
    Gb.Refresh
    
End Sub

Sub homebut_clicked(Target As String)
    ABMShared.NavigateToPage(ws,"HomePage","../HomePage/")
End Sub

Sub newbut_clicked(Target As String)
    Act.EdtMode = False
    ABMShared.NavigateToPage(ws,Act.EntryPage(Act.Index),$"../${Act.EntryPage(Act.Index)}/"$)
End Sub

Sub edtbut_clicked(Target As String)
    Act.EdtMode = True
    ABMShared.NavigateToPage(ws,Act.EntryPage(Act.Index),$"../${Act.EntryPage(Act.Index)}/"$)
End Sub

Sub page_modalsheetready(Target As String)
    
End Sub

Sub nufarmbut_clicked(Target As String)
    Act.Nu = "Farm"
    msNuClient.SetupEntryPt(page.ModalSheet("NuClientMS"))
    page.ShowModalSheet("NuClientMS")   
End Sub

Sub nupadbut_clicked(Target As String)
    Act.Nu = "Paddock"
    msNuClient.SetupEntryPt(page.ModalSheet("NuClientMS"))
    page.ShowModalSheet("NuClientMS")
End Sub

Sub farmcbx_clicked(Target As String)
    Dim idx As Int = Target
    PD.Farms.SetCurrIndx(idx)            'Currfarm = PD.farms.Get(Target)
    Log($"Current farm is ${PD.Farms.GetCurrVal("Name")}, ID = ${PD.Farms.GetCurrVal("ID")}"$)
    PD.Paddocks.LoadWhere($"FarmID = ${PD.farms.GetCurrVal("ID")}"$,"Name") 
    Dim Pc As ABMCombo = page.Component("PadCBX")
    Act.FillCombo(page,Pc,PD.paddocks.SelectedData)
    Pc.Visibility=ABM.VISIBILITY_ALL
    Dim B As ABMButton = page.Component("NuPadBut")
    B.Visibility = ABM.VISIBILITY_ALL
    Pc.Refresh
    B.Refresh
End Sub

Sub clientcbx_clicked(Target As String)
    PD.Clients.SetCurrIndx(Target)
    Log($"Current client is ${PD.Clients.GetCurrVal("Name")} ID = ${PD.Clients.GetCurrVal("ID")} "$)
    PD.Clients.DataRpt
    Dim Fc As ABMCombo = page.Component("FarmCBX")
    PD.Farms.LoadWhere($"ClientID = ${PD.Clients.GetCurrVal("ID")}"$,"")
    If PD.Farms.Size > 0 Then
        Act.FillCombo(page,Fc,PD.Farms.SelectedData)
    else if PD.Farms.Size = 1 Then
        Fc.SetActiveItemId("1")
        Fc.SetFocus
    End If
    Dim B As ABMButton = page.Component("NuFarmBut")
    B.Visibility = ABM.VISIBILITY_ALL
    Fc.Visibility = ABM.VISIBILITY_ALL
    Fc.Refresh
    B.Refresh
End Sub


#end region

#Region ABMPage
' clicked on the navigation bar
Sub Page_NavigationbarClicked(Action As String, Value As String)
    ' saving the navigation bar position
    page.SaveNavigationBarPosition
    If Action = "LogOff" Then
        ABMShared.LogOff(page)
        Return
    End If

    ABMShared.NavigateToPage(ws, ABMPageId, Value)
End Sub

Sub Page_DebugConsole(message As String)
    Log("---> " & message)
End Sub
#end region

Also here is main

B4X:
'Non-UI application (console / server application)
#Region  Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True     
#End Region
#AdditionalJar: sqlite-jdbc-3.7.2

Sub Process_Globals
    Public srvr As Server
    Dim ABM As ABMaterial 'ignore
    Dim port As Int = 50002
End Sub

Sub AppStart (Args() As String)
    ' the user needs to login
    ABMShared.NeedsAuthorization = False
    
    ' Build the Theme
    ABMShared.BuildTheme("mytheme")   
    Act.ButColor = ABM.COLOR_YELLOW
    ' create the app
    Dim myApp As ABMApplication
    myApp.Initialize
    
    PD.Init
    ' create the pages
    Dim sPadPage As SelectPaddockPage
    sPadPage.Initialize
    
    Dim SDpage As SowDataPage
    SDpage.Initialize   
    
    Dim stPage As SeedTypePage
    stPage.Initialize
    
    Dim StartPage As HomePage
    StartPage.Initialize
    
    Dim SprayDP As SprayDataPage
    SprayDP.Initialize
    
    Dim ObsPage As ObservPage
    ObsPage.Initialize
    
    ' add the pages to the app
    myApp.AddPage(sPadPage.page)
    myApp.AddPage(SDpage.page)
    myApp.AddPage(stPage.page)
    myApp.AddPage(StartPage.page)
    myApp.AddPage(SprayDP.page)
    myApp.AddPage(ObsPage.page)
    
    ' start the server
    myApp.StartServer(srvr, "srvr", port)   
            
    'ABMShared.RedirectOutput(File.DirApp, "logs.txt")
    
    #If DEBUG
        ' in debug mode, start the browser and open the app on all devices (DOES NOT WORK IF EDGE IS YOUR DEFAULT BROWSER!)
        'ABM.ViewerOpenAllDevices("http://localhost:" & port & "/" & ABMShared.AppName & "/", 100)
        
        ' or open a specific device as default (DOES NOT WORK IF EDGE IS YOUR DEFAULT BROWSER!)
        'ABM.ViewerOpenDevice("http://localhost:" & port & "/" & ABMShared.AppName & "/", 300, ABM.VIEWER_TABLET)
        
        ' or just open de browser, no multiple devices
        'ABM.ViewerOpen("http://localhost:" & port & "/" & ABMShared.AppName & "/")
    #End If
            
    StartMessageLoop
End Sub

and just so it's all together here is the exception. Note top line from the log() command
"At SelectPaddockPage.Initialize
Error occurred on line: 23
java.lang.NullPointerException
at com.ab.abmaterial.ABMPage.Refresh(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at anywheresoftware.b4a.shell.Shell.runVoidMethod(Shell.java:676)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:240)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:167)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:91)
at anywheresoftware.b4a.shell.ShellBA.raiseEvent2(ShellBA.java:98)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:78)
at com.ab.template.main.main(main.java:29)"
 
Upvote 0

MichalK73

Well-Known Member
Licensed User
Longtime User
Wrong procedure. It just has to be
B4X:
'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    ' build the local structure IMPORTANT!
    BuildPage       
End Sub
 
Upvote 0

alwaysbusy

Expert
Licensed User
Longtime User
Page.Refresh may not do what you think it does. It does not completely 'refresh' as in pressing F5 in the browser. What it does internally is pushing the changes you made to the page in B4J to the browser. this 'refresh' can be done on several levels (e.g. Container.Refresh, Input.Refresh) to speed things up.

I will have to look into the page.IsInitialized thing, as at first sight, you do not do anything wrong here (but indeed shouldn't be done here). I did had to use some 'Java tricks' in the library to allow serializing the Page and Websocket object (so if a connection is lost, it could be retrieved on reconnecting) which does not allow you to do it in the Initialize method. Key may here be: do not do a .Refresh, unless it first has passed through the WebSocket_Connected method.

The thing you are looking for is probably a complete refresh of the page. In that case you were right that it should be done with the ABMShared.NavigateToPage method. Its signature can be modified as needed, e.g. in my latest project, it looks like this:

B4X:
Public Sub NavigateToPage(ws As WebSocket, PageId As String, TargetUrl As String, OpenInNewTab As Boolean)   
    ' here it does remove the page from the cache too 
    If PageId.Length > 0 Then ABM.RemoveMeFromCache(CachedPages, PageId)
    If ws.Open Then
        If OpenInNewTab Then
            Dim s As String           
            ' check if a mobile phone or a tablet
            s = $"var check = false;
              (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
               if (check) {
                  window.location = arguments[0];
              } else {
                window.open(arguments[0],'_blank');                 
              }"$           
            ws.Eval(s, Array As Object(TargetUrl))                           
        Else
            ws.Eval("window.location = arguments[0]", Array As Object(TargetUrl))           
        End If
        ws.Flush
    End If
End Sub

It can be placed virtually everywhere, as long as it has a WebSocket. Note that this will completely reload the page (as if you have pressed CTRL+F5 in the browser). It may even create a new session.

Can you ellaborate a bit on what exactly you are trying to archive? (e.g. reloading a table with new data or something like that)

Alwaysbusy
 
Last edited:
Upvote 0

Rob White

Member
Licensed User
This project involves entry of Paddock data (Sowing, Chemical, harvest etc) from our farms.
It is paddock centric. Select the paddock and then the respective data.
My problem is when I revisit a page the all data "input" components (ABMInput, ABMCombo ...) do not show.
As an example here is the main menu page all buttons.
MainMenu.png

If I click the spraying button I get:-

SelectClient.png

Where you select the client and the farm combo is shown and then the paddock combo.

So you end up with:-
SelectPaddockOK.png

For this example clicking the home button takes you back to the Main menu page. Other two are edit last spraying activity or create a new one (same deal with both these).

Then clicking spraying again gives this:-
SelectPaddockOK.png
Components missing and "inactive"(no data inputs) components shown when they should be hidden.

So obviously I need to refresh the page or get the code in the correct place. See post #5 above for the code.
Remember this is my first try at seriously using B4J and ABMaterial
Hoping this is all you need to point me in the right direction.

Rob White
 
Upvote 0

Rob White

Member
Licensed User
Just to update and give a little further evidence to my problem.
I have found an old Win XP box, reformatted the HD and installed Ubuntu 20 on it. My first attempt at Linux!

I have installed my app and have it running but there is still the problem of incomplete pages being loaded.
For example the select paddock page shows but there is no data in the Client dropdown - the word Client is grayed out! This is not a Db problem I put some code to log the clients and this displays in the terminal output (not using nohup for this testing). The b4j-2021_07_19.request.log shows the requests OK to my eyes.

Another an interesting fact. Installing B4JSDemo gives similar problems, sort of corrected by reloading. This problem is I see EITHER the menu or the page contents BUT never both.

Are there any other jetty logs I should look at?

Hoping this helps.
 
Upvote 0

MichalK73

Well-Known Member
Licensed User
Longtime User
I don't know if I understand you well without full code, but I think I used to have something like that. If that's what I think, then I bypassed the cache when loading a page for that page and always called ConnectPage. Back then, I always had components.
 
Upvote 0

Rob White

Member
Licensed User
I had not copied the .needs file. This has changed the symptoms on the server to exactly the same as my development machine.

Commenting out the line below solves/works around the problem.

B4X:
ABM.UpdateFromCache(Me, ABMShared.CachedPages, ABMPageId, ws) 
in the sub WebSocket_Connected
No other code changed/added.
Hope it does not slow things too much.

If anyone wants to pursue this problem further I am only too glad to provide code or access to my test server.
 
Upvote 0

Rob White

Member
Licensed User
OK will keep that in mind. In the case of the paddock selection page I am only showing one extra combo at a time. Of course that is not true for the buttons though.
 
Upvote 0
Top