Android Question What is going on with setting values to this type variable?

JohnC

Expert
Licensed User
Longtime User
I have a custom type:

B4X:
    Type FavFormat(Id As Int, Name As String, Tel As String)

I then have a routine that loads records from a database and fills the type, which is then added to a list.

So, I tried this code first, where the DIM and .INITIALIZE is done outside the loop:

B4X:
Dim F As FavFormat
    F.Initialize   

    Cur = SQL.ExecQuery("SELECT * FROM favs order by sort")

    For Row = 0 To Cur.RowCount -1
        Cur.Position = Row

        F.Tel = Cur.GetString("ctel")       
        F.Name = Cur.GetString("cname")
        F.Id = Cur.GetString("cid")
       
        GridItems.Add(F)
       
    Next

But this results in all the .Name properties in the list being the same value and not unique as they are in the database.

So I tried initializing the type inside the loop thinking that it will "reset" the type var to null values so it can be used again:

B4X:
Dim F As FavFormat

    Cur = SQL.ExecQuery("SELECT * FROM favs order by sort")

    For Row = 0 To Cur.RowCount -1
        Cur.Position = Row

        F.Initialize   
        F.Tel = Cur.GetString("ctel")       
        F.Name = Cur.GetString("cname")
        F.Id = Cur.GetString("cid")
       
        GridItems.Add(F)
       
    Next

But this results in the same problem of all the .name values being the same.

So, then I moved BOTH the dim and init inside the loop and then everything was working OK:

B4X:
    Cur = SQL.ExecQuery("SELECT * FROM favs order by sort")

    For Row = 0 To Cur.RowCount -1
        Cur.Position = Row

        Dim F As FavFormat
        F.Initialize   
       
        F.Tel = Cur.GetString("ctel")       
        F.Name = Cur.GetString("cname")
        F.Id = Cur.GetString("cid")
       
        GridItems.Add(F)
       
    Next

Why did I have to have the DIM and Init in the loop?
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0
Top