Android Question How do I create an array of unknown size?

omarruben

Active Member
Licensed User
Longtime User
B4X:
Type person (name as string, lastname as string)

dim listofpeople() as person

listofpeople(0).name ="rufus"     ' error

something like that is not working
 

Computersmith64

Well-Known Member
Licensed User
Longtime User
B4X:
Type person (name as string, lastname as string)

dim listofpeople() as person

listofpeople(0).name ="rufus"     ' error

something like that is not working
Use a List.
B4X:
Type person (name As String, lastName As String)
Dim listOfPeople As List

listOfPeople.add(person("Wayne", "Kerr"))
(or something - it's been a while since I've written anything in B4X)

- Colin.
 
Upvote 1

Star-Dust

Expert
Licensed User
Longtime User
B4X:
Type person (name As String, lastname As String)

Sub Main
  Dim listofpeople() As person

  Listofperson=AddPerson(listofpeople,"John","Do")
  Listofperson=AddPerson(listofpeople,"Jack","Screamer")
End Sub


Sub AddPerson(ArrPeople() As Person, name As String, lastname As String) As Person()
  Dim ArrP(ArrPeople.Size+1) As Person
  Dim P As Person

  P.Initialize
  P.name=name
  P.lastname=lastname

  For i=0 to ArrPeople.size-1
    ArrP(i)=ArrPeople(i)
  Next

  ArrP(ArrPeople.size)= P

  Return ArrP
End Sub
 
Upvote 2

Daestrum

Expert
Licensed User
Longtime User
Alternative to Star-Dust's code
B4X:
    Dim Arrays As JavaObject
    Type person(name As String, lastname As String)
    Dim people() As person

Sub someSub 
   Arrays.InitializeStatic("java.util.Arrays")
    For a = 0 To 10
        addPerson( Createperson( "fred" & a , "Bloggs"))
    Next

    For Each human As person In people
        Log(human.name & " " & human.lastname)
    Next
End Sub

Sub addPerson(newbie As person)
    'copy array to itself and increase size by 1
    people = Arrays.RunMethodJO("copyOf",Array(people , people.Length+1)) 'ignore
    'add the new person at the end of array
    people(people.Length - 1) = newbie
End Sub

' created by the Type definition
Public Sub Createperson (name As String, lastname As String) As person
    Dim t1 As person
    t1.Initialize
    t1.name = name
    t1.lastname = lastname
    Return t1
End Sub
 
Upvote 1
Cookies are required to use this site. You must accept them to continue using the site. Learn more…