Lists and Classes

socialnetis

Active Member
Licensed User
Longtime User
Hi, I have a very Small class that emulates a tuple:
B4X:
'Class module
Sub Class_Globals
   Dim Title As String
   Dim Image As String         'Image Link
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(mTitle As String, mImage As String)
   Title = mTitle
   Image = mImage
End Sub

And I would like to use a single Tuple in a loop, which in each loop changes, and put that tuple into a list. Something like this (I'm reading some Lines from a file):

B4X:
Dim mTuple As Tuple
Dim mList As List
mList.Initialize
Do While Line <> Null
    Title1 = ParseTitle(Line)
    Image1 = ParseImage(Line)
    mTuple.Initialize(Title1,Image1)
    mList.Add(mTuple)
Next

The problem I'm having is that at the end of the loop, all the elements of the List are like the Last element (same title, and image). I guess that this is because the Class are used like Pointers in C or C++.

How can I use a generic Tuple that holds the information in each loop, and add it to a list?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Two solutions:
B4X:
Do While Line <> Null
    Title1 = ParseTitle(Line)
    Image1 = ParseImage(Line)
    Dim mTuple As Tuple 'creates a new object
    mTuple.Initialize(Title1,Image1)
    mList.Add(mTuple)
Next

2:
B4X:
Sub CreateTuple(Title As String, Image As String) As Tuple
 Dim t As Tuple
 t.Initialize(Title, Image)
 Return t
End Sub

Do While Line <> Null
    Title1 = ParseTitle(Line)
    Image1 = ParseImage(Line)
    mList.Add(CreateTuple(Title1, Image1))
Next
 
Upvote 0
Top