B4J Question Reduce repetitive code for classes

jroriz

Active Member
Licensed User
Longtime User
Hi everyone.

Is there a better way to write the code below?

B4X:
Sub MenuBar1_Action
    Dim mi As MenuItem = Sender

    If mi.Text = "Users" Then
        Dim us As Users  ' general class
        us.Initialize
    End If

    If mi.Text = "Unity" Then
        Dim un As Unity
        un.Initialize
    End If
   
End Sub

The above code repeats for each menu option, always creating a class whose name matches the menu name
 

Derek Johnson

Active Member
Licensed User
Longtime User
Not quite sure what your problem is but how about this:

B4X:
Sub MenuBar1_Action
    Dim mi As MenuItem = Sender
    select case mi.text
    case "Users"
        Dim us As Users  ' general class
        us.Initialize
    case "Unity"
        Dim un As Unity
        un.Initialize
    End case
 
End Sub
 
Upvote 0

jroriz

Active Member
Licensed User
Longtime User
It's not exactly a problem.
What I do not want is to keep repeating the same portion of code pretty much the same for each menu item.
 
Upvote 0

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
i am not sure why you need it that way but it is like this:

B4X:
Sub MenuBar1_Action
    Dim mi As MenuItem = Sender

     dim jo as JavaObject = createNewClass(mi.text) 'You can do with this object whatever you like. 

End Sub

Sub createNewClass(newClass As String) As JavaObject
    Dim jo As JavaObject
    jo.InitializeNewInstance("b4j.example."&newClass,Null) 'b4j.example is the name of your package written in the IDE -> Project -> Build Configurations.
    Return jo
End Sub
 
Upvote 0

jroriz

Active Member
Licensed User
Longtime User
Your code did not give an error, but the sub initialize did not fire ...

My class is a standard class (created in "Project / add new module / class module").

Looking at the thread "[solved] Create Class Instance From Variable" I guess what I want will not be possible without the repetitive code ...
 
Upvote 0
Top