B4J Question Strange Operation with List & Type

incendio

Well-Known Member
Licensed User
Longtime User
Hello,

I have these codes
B4X:
Sub Process_Globals
    Private MainForm As Form
    Type Col(Val As String,theme As String)
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   MainForm = Form1
   Private Cols As List
   Private TblCol,Vl As Col
   Cols.Initialize

   For i = 1 To 2
     TblCol.Initialize
     TblCol.Val = "Col" & i
     TblCol.theme = i
     Cols.Add(TblCol)
   Next

   Vl.Initialize
   Vl = Cols.Get(0)
   Log("Value : " & Vl.Val & " Theme : " & Vl.theme)

   Vl = Cols.Get(1)
   Log("Value : " & Vl.Val & " Theme : " & Vl.theme)
End Sub

Log shows :
Value : Col2 Theme : 2
Value : Col2 Theme : 2

This code
B4X:
Vl = Cols.Get(0)
always returns last item in the List.

Where did I miss?
 

DonManfred

Expert
Licensed User
Longtime User
It is not strange... You are reusing the same object...

Move the dim inside the loop to generate a NEW instance on each iteration
B4X:
Sub Process_Globals
    Private MainForm As Form
    Type Col(Val As String,theme As String)
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   MainForm = Form1
   Private Cols As List
   Cols.Initialize

   For i = 1 To 2
     Private TblCol As Col
     TblCol.Initialize
     TblCol.Val = "Col" & i
     TblCol.theme = i
     Cols.Add(TblCol)
   Next
   Private Vl As Col
  ' work with VI
 
Upvote 0
Top