Android Question Declarations for Media Player Polymorphism

GuyBooth

Active Member
Licensed User
Longtime User
I have a class in which I want to be able to select a different type of media player depending on how the class is initialized. (I want to achieve Polymorphism).
Problem is, the Type has to be declared right up front, in the Class Globals.

If I try to say this:
B4X:
If Player_Type = "Stream" Then
    Public MP As MediaPlayerStream
else if Player_Type = "Local" Then
    Public MP As MediaPlayer           
End If
I get this error:
B4X:
Current declaration does not match the previous one
I've tried a few different variations without success. Anyone have any thoughts on how to achieve this?
 

GuyBooth

Active Member
Licensed User
Longtime User
You can create two classes, one with MediaPlayer and one with MediaPlayerStream. You can then use CallSub to call common subs.

I did it this way, and it works, but still doesn't have the elegance I was looking for - I still can't "conditionally" declare one type or the other.
As in the example above, I can't say:
B4X:
If Player_Type = "Stream" then
   Public MP as clStreamPlayer
else if Player_Type = "Local" then
  Public MP as clLocalPlayer
End if

any more than I can say:
B4X:
If Player_Type = "Stream" Then
    Public MP As MediaPlayerStream
else if Player_Type = "Local" Then
    Public MP As MediaPlayer         
End If

BUT - I did find another solution:

B4X:
Sub Class_Globals
    Public MP As MediaPlayer
    Private MP0 As MediaPlayer
    Private MP1 As MediaPlayerStream
    Private joMP As JavaObject
End Sub

Public Sub Initialize(oCallBack As Object, sPlayerName As String, iPlayerType As Int)
    Callback = oCallBack
    Player_Name = sPlayerName
    PlayerType = iPlayerType
    ' Set up the player
    If PlayerType = LOCAL Then
        MP0.Initialize2("MP")
        joMP = MP0
    else if PlayerType = STREAM Then
        MP1.Initialize("MP")
        joMP = MP1
    End If 
End Sub
' Play the loaded track - continue if it was paused
Sub Play_()
    ' If it was already playing, return True
   If Track_Loaded Then
      If Not(joMP.RunMethod("IsPlaying", Null)) Then
         joMP.RunMethod("Play", Null)
       End If
   End If
End Sub

Now when I make any call within the class to joMP it uses the correct player. I had to dig around and experiment to find what the calls are in a JavaObject - but that's a subject for a different thread.
Calling for the class to Play, for example, now doesn't have to be concerned about which type was previously initialized - I can simply call the class Play_ routine.
 
Last edited:
Upvote 0
Top