Android Tutorial Variables & Objects in Basic4android

Discussion in 'Tutorials & Examples' started by Erel, Mar 24, 2011.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Types

    Basic4android type system is derived directly from Java type system.
    There are two types of variables: primitives and non-primitives types.
    Primitives include the numeric types: Byte, Short, Int, Long, Float and Double.
    Primitives also include: Boolean and Char.
    List of types with their ranges: http://www.basic4ppc.com/forum/basi...tutorials/8062-data-type-range.html#post45511

    Primitive types are always passed by value to other subs or when assigned to other variables.
    For example:
    Code:
    Sub S1
     
    Dim A As Int
     A = 
    12
     S2(A)
     
    Log(A) 'Prints 12
    End Sub

    Sub S2(B As Int)
     B = 
    45
    End Sub
    All other types, including arrays of primitives types and strings are categorized as non-primitive types.
    When you pass a non-primitive to a sub or when you assign it to a different variable, a copy of the reference is passed.
    This means that the data itself isn't duplicated.
    It is slightly different than passing by reference as you cannot change the reference of the original variable.

    All types can be treated as Objects.
    Collections like lists and maps work with Objects and therefore can store any value.
    Here is an example of a common mistake, where the developer tries to add several arrays to a list:
    Code:
    Dim arr(3As Int
    Dim List1 As List
    List1.Initialize
    For i = 1 To 5
     arr(
    0) = i * 2
     arr(
    1) = i * 2
     arr(
    2) = i * 2
     List1.Add(arr) 
    'Add the whole array as a single item
    Next
    arr = List1.Get(
    0'get the first item from the list
    Log(arr(0)) 'What will be printed here???
    You may expect it to print 2. However it will print 10.
    We have created a single array and added 5 references of this array to the list.
    The values in the single array are the values set in the last iteration.
    To fix this we need to create a new array each iteration.
    This is done by calling Dim each iteration:
    Code:
    Dim arr(3As Int 'This call is redundant in this case.
    Dim List1 As List
    List1.Initialize
    For i = 1 To 5
     
    Dim arr(3As Int
     arr(
    0) = i * 2
     arr(
    1) = i * 2
     arr(
    2) = i * 2
     List1.Add(arr) 
    'Add the whole array as a single item
    Next
    arr = List1.Get(
    0'get the first item from the list
    Log(arr(0)) 'Will print 2
    Tip: You can use agraham's CollectionsExtra library to copy an array.

    Casting


    Basic4android casts types automatically as needed. It also converts numbers to strings and vice versa automatically.
    In many cases you need to explicitly cast an Object to a specific type.
    This can be done by assigning the Object to a variable of the required type.
    For example, Sender keyword returns an Object which is the object that raised the event.
    The following code changes the color of the pressed button. Note that there are multiple buttons that share the same event sub.
    Code:
    Sub Globals
        
    Dim Btn1, Btn2, Btn3 As Button
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        Btn1.Initialize(
    "Btn")
        Btn2.Initialize(
    "Btn")
        Btn3.Initialize(
    "Btn")
        
    Activity.AddView(Btn1, 10dip10dip200dip50dip)
        
    Activity.AddView(Btn2, 10dip70dip200dip50dip)
        
    Activity.AddView(Btn3, 10dip130dip200dip50dip)
    End Sub

    Sub Btn_Click
        
    Dim b As Button
        b = 
    Sender 'Cast the Object to Button
        b.Color = Colors.RGB(Rnd(0255), Rnd(0255), Rnd(0255))
    End Sub
    The above code could also be written more elegantly:
    Code:
    Sub Globals

    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    For i = 0 To 9 'create 10 buttons
            Dim Btn As Button
            Btn.Initialize(
    "Btn")
            
    Activity.AddView(Btn, 10dip10dip + 60dip * i, 200dip50dip)
        
    Next
    End Sub

    Sub Btn_Click
        
    Dim b As Button
        b = 
    Sender
        b.Color = 
    Colors.RGB(Rnd(0255), Rnd(0255), Rnd(0255))
    End Sub
    Scope

    Variables that are declared in Sub Globals or Sub Process_Globals are global and can be accessed from all subs.
    Other variables are local and can only be accessed from the sub that they are declared in.
    See the Activity lifecycle tutorial for more information about Globals vs. Process_Globals variables.

    Tips

    All views types can be treated as Views. This allows you to change the common properties of views easily.
    For example, the following code disables all views that are direct children of the activity:
    Code:
    For i = 0 To Activity.NumberOfViews - 1
        
    Dim v As View
        v = 
    Activity.GetView(i)
        v.Enabled = 
    False
    Next
    If we only want to disable buttons:
    Code:
    For i = 0 To Activity.NumberOfViews - 1
        
    Dim v As View
        v = 
    Activity.GetView(i)
        
    If v Is Button Then 'check whether it is a Button
            v.Enabled = False
        
    End If
    Next
    The Type keyword allows you to create your own type of objects. Custom types behave exactly like other non-primitive types.
     
  2. anormal

    anormal Member Licensed User

    Wow! very nice introduction about vars and objects.

    I think more of these basic introductions could be written about other things B4A

    i've been a "classic" programmer for years (php,a lot of delphi,...) and programming in Android is very different of the classic windows world.

    thanks!
     
  3. Lordshiva1948

    Lordshiva1948 Member Licensed User

    Yes I do agree with other person that this vars and objects tutorial is very helpful for those are new to programing:sign0087:
     
  4. Ennesima77

    Ennesima77 Member Licensed User

    Hi everybody,
    first of all sorry for my "maccheronic" English and my less experience.
    I'm use to program in VB (not like a pro but like a joke), my first problem was how can I open a new form the main?
    for the moment I just take a look on B4A IDE, and I build my first Form with 2 button, one of those (in my idea) open a new form (friends details for example).

    In old VB i use to declare the varibles

    DIM Pippo as frmPippo
    Pippo.Show

    Thanks to everyone who want to help me!:sign0188:
     
  5. Roeschti

    Roeschti Member Licensed User

    You should study the Beginners Guide. There are no Forms in Android, only Activities
     
  6. miguelconde

    miguelconde Member Licensed User

    I'm trying to pass a "cursor" object by reference to a function, when used within the function generates an initialization error. Is supposed to be initialized before the function call. Can you pass initialized objects to a functions and sub?

    Thank you.
     
  7. Erel

    Erel Administrator Staff Member Licensed User

    There should not be a problem passing an initialized object. Are you sure that the object is already initialized?
     
  8. naruto

    naruto Member Licensed User

    Is there any way to initialize a variable directly at declaration?

    For example:
    Dim summary As String = "Summary of results"

    I tried to declare it as done in Microsoft VB but couldn't get it working, see url
    Dim Statement (Visual Basic)

    Thanks for the support.
     
  9. klaus

    klaus Expert Licensed User

    No.

    I do it that way:
    Code:
    Dim summary As String   : summary = "Summary of results"
    Best regards.
     
  10. naruto

    naruto Member Licensed User

    Thanks for the reply Klaus, this solution is definitely better than nothing.

    Code:
    Dim summary As String   : summary = "Summary of results"
    Just curious though, what does ": summary " exactly do?
     
  11. flandersdl

    flandersdl Member Licensed User

    The : is just like in VB, it starts a new statement on the same line.

    Code:
    Dim summary As String   : summary = "Summary of results"
    is the same as :
    Code:
    Dim summary As String
    summary = 
    "Summary of results"
     
  12. naruto

    naruto Member Licensed User

    I get it, thanks for the explanation. So instead of a ";" like in many languages I get to use ":".
     
  13. roboto

    roboto New Member

    Are you able to use a function to convert a string of numbers into an integer?
     
  14. Erel

    Erel Administrator Staff Member Licensed User

    Please start a new thread for this question.
     
  15. cbal03

    cbal03 Member Licensed User

    Is there a way to determine the type of an object / variable? I have some javascript returning [object object] which is actually ["text":"hello world"]. I need to extract "hello world" from the response. I am using the JSON lib to no avail.

    Thanks.
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    You can use Is keyword to find the object type. I recommend you to start a new thread and post the JSON string you are trying to parse.
     
  17. Martin Domian

    Martin Domian New Member Licensed User

    How is it possible to terminate a object like in VB, wenn I do not need it any more or shout not carry any datas

    VB Set Obj = nothing
    VBA ?
     
  18. Erel

    Erel Administrator Staff Member Licensed User

    Unless the variable is a global variable then it is no needed as the reference will be removed automatically when the variable scope ends.

    Even if the variable is a global variable then it is not needed as the previous one will be replaced when you create a new object.

    With that said you can write: SomeObject = Null.
     
  19. Martin Domian

    Martin Domian New Member Licensed User

    Thanks!
    Yes, NULL easy, sorry. I need to set it to Null, because some subs need it
     
  20. omarruben

    omarruben Member Licensed User

    Hi guys, i have a simple problem :
    i have a first column of edittext place in order (edittext_1, edittext_2,etc) (10)
    i have a second edittext column with (edittext_1_val,edittext_2_val,etc)(10)
    i need to get their text values in order (edittext_1.text and edittext_1_val ) in a loop(1-10)
    i have tried typecasting with not results.

    how i can do something like
    dim temp1,temp2 as edittext
    for i=1 to 10
    temp1 = edittext_(i).text
    temp2 = edittext_(i)_val.text
    next

    thanks
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice