I am starting a new project and learning about the starter service.
In the past I have been Initializing SQL objects in a code module, and then calling the code from the Main module.
For Example..
Code Module: MyCodeModule
B4X:
Public Sub InitializeDatabase
If Database.IsInitialized = False Then
If File.Exists(File.DirInternal,"MyDatabase.db") = True Then
Database.Initialize(File.DirInternal,"MyDatabase.db",False)
Return
End If
If File.Exists(File.DirInternal,"MyDatabase.db") = False Then
Database.Initialize(File.DirInternal,"MyDatabase.db",True)
CreateAppDatabase ' this will create tables etc. in the database from another sub in the code module
Return
End If
End If
End Sub
Main Module:
B4X:
Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
MyCodeModule.InitializeDatabase
End If
End Sub
The above seems to work.
However, when using the starter service, should I do:
Service: Starter
B4X:
Sub Service_Create
MyCodeModule.InitializeDatabase
End Sub
Main Module:
B4X:
Sub Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
StartService(Starter)
End if
End Sub
Would the above work if I move the code from the Main module to the starter service? Or do I need to Initialize the SQL object in the service module and not the code module ?
You should initialize it from Service_Create as there can be cases where the main module is not started at all.
You can also move the database to the starter service and initialize it from Service_Create. Both options are good. For a new project I would have recommended to put it in the Starter service.
May be wrong, but I think it isn't exactly a "should". He recommends to declare the db in the Starter service, and initialize it from Starter Service_Create since it is the very first entry into the application and will always be executed.
The choice of whether the initialization and/or other db-related code can be in a dedicated code module or in the starter service itself depends on how you want to structure your code or keep it modular for other apps, but it should make no difference.
The advantage of moving the database code to the starter service is that services can handle events while code modules can't. This will allow you in the future to use the asynchronous SQL methods.