0% found this document useful (0 votes)
29 views10 pages

Unit 3-MAD

Mobile application development
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views10 pages

Unit 3-MAD

Mobile application development
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Mobile Application Development

UNIT 3
Process and Activity life cycle
Variables and Objects:
A variable is a symbolic name given to some known or unknown quantity or information, for the
purpose of allowing the name to be used independently of the information it represents. A
variable name in computer source code usually associated with a data storage location and
thus also its contents, and these may change during the course of program execution (source
Wikipedia). 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

Variable Types

List of types with their ranges:

Rasure B. BPage
From Google
Mobile Application Development

List of types with their ranges:


Numeric types:
Byte 0 - 255
Int (2 bytes) -32768 - 32768.

Other types:
Boolean True or False.
Practically it is saved as a byte with the value of 1 or 0.
String
Strings are made from an array of bytes that end with a null byte (byte with the value of 0).
Object
Objects can hold other types of values.

Primitive types are always passed by value to other subs or when assigned to other variables.
For example:
Sub S1
Private A As Int
A = 12 The variable A = 12
S2(A) It's passed by value to routine
S2 Log(A) ' Prints 12 Variable A still equals 12, even though B was changed in routine
S2.
End Sub

Sub S2(B As Int) Variable B = 12


B = 45 Its value is changed to B = 45
End Sub

All other types, including arrays of primitive 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

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 Private each iteration:

Private arr(3) As Int 'This call is redundant in this case.


Private List1 As List
List1.Initialize
For i = 1 To 5
Private arr(3) As Int
arr(0) = i * 2
arr(1) = i * 2
arr(2) = i * 2
Rasure B. BPage
From Google
Mobile Application Development

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 2Private arr(3) As Int
Private 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???

Names of variables
It is up to you to give any name to a variable, except reserved words.
A variable name must begin with a letter and must be composed by the following
characters A-Z, a-z, 0-9, and underscore "_", no spaces, no brackets etc.
Variable names are case insensitive, that means that Index and index refer to the same
variable.

Example:
Interest = Capital * Rate / 100 is meaningful
n1 = n2 * n3 / 100 not meaningful
it is useful to add to the name a three character prefix that defines its type.

Examples:
lblCapital lbl > Label Capital > purpose
edtInterest edt > EditText Interest > purpose
btnNext btn > Button Next > purpose

Declaring variables
Simple variables
Variables are declared with the Private or the Public keyword followed by the variable name
and the As keyword and followed by the variable type.

There exist the Dim keyword, this is maintained for compatibility.

Examples:

Private Capital As Double Declares three variables as Double,


Private Interest As Double double precision numbers.
Private Rate As Double

Private i As Int Declares three variables as Int, integer numbers.


Private j As Int
Private k As Int

Rasure B. BPage
From Google
Mobile Application Development

Private lblCapital As Label


Private lblInterest As Label Declares three variables as Label views.
Private lblRate As Label

Private btnNext As Button Declares two variables as Button views.


Private btnPrev As Button

The same variables can also be declared in a short way.

Private Capital, Interest, Rate As Double


Private i, j, k As Int
Private lblCapital, lblInterest, lblRate As Label
Private btnNext, btnPrev As Button

The names of the variables separated by commas and followed by the type declaration.

Following variable declarations are valid:

Private i = 0, j = 2, k = 5 As Int
Private txt = "test" As String, value = 1.05 As Double, flag = False As Boolean

View names must be declared if we want to use them in the code.

For example, if we want to change the text in a Label view in the code, like
lblCapital.Text = "1200",

we need to reference this Label view by its name lblCapital, this is done with the Private
declaration.

If we never make any reference to this Label view anywhere in the code no declaration is
needed.
Using an event routine for that view doesn't need a declaration either.

To allocate a value to a variable write its name followed by the equal sign and followed by
the value, like:
Capital = 1200
LastName = "SMITH"

Note that for Capital we wrote just 1200 because Capital is a number.
But for LastName we wrote "SMITH" because LastName is a string.
Strings must always be written between double quotes.

Array variables
Arrays are collections of data or objects that can be selected by indices. Arrays can have
multiple dimensions.
The declaration contains the Private or the Public keyword followed by the variable name
LastName, the number of items between brackets (50), the keyword As and the variable type
String
.

Rasure B. BPage
From Google
Mobile Application Development

There exist the Dim keyword, this is maintained for compatibility.

Examples:
Public LastName(50) As String One dimension array of strings, total number of items 50.
Public Matrix(3, 3) As Double Two dimensions array of Doubles, total number of items 9.
Public Data(3, 5, 10) As Int Three dimensions array of integers, total number of items 150.
The first index of each dimension in an array is 0.
LastName(0), Matrix(0,0), Data(0,0,0)
The last index is equal to the number of items in each dimension minus 1.
LastName(49), Matrix(2,2), Data(2,4,9)
Public LastName(10) As String
Public FirstName(10) As String
Public Address(10) As String
Public City(10) As String
or

Public LastName(10), FirstName(10), Address(10), City(10) As String

This example shows how to access all items in a three dimensional array.
Public Data(3, 5, 10) As Int
For i = 0 To 2
For j = 0 To 4
For k = 0 To 9
Data(i, j, k) = ...
Next
Next
Next

A more versatile way to declare arrays is to use variables.


Public NbPers = 10 As Int
Public LastName(NbPers) As String
Public FirstName(NbPers) As String
Public Address(NbPers) As String
Public City(NbPers) As String

We declare the variable Public NbPers = 10 As Int and set its value to 10.
Then we declare the arrays with this variable instead of the number 10 as before.
The big advantage is if at some point we need to change the number of items, we change
only ONE value.

For the Data array we could use the following code.


Public NbX = 2 As Int
Public NbY = 5 As Int
Public NbZ = 10 As Int
Public Data(NbX, NbY, NbZ) As Int

And the access routine.

For i = 0 To NbX - 1
For j = 0 To NbY - 1

Rasure B. BPage
From Google
Mobile Application Development

For k = 0 To NbZ - 1
Data(i, j, k) = ...
Next
Next
Next
Filling an array with the Array keyword :
Public Name() As String
Name = Array As String("Miller", "Smith", "Johnson", "Jordan")

Constant variables Const keyword


Const variables are constant variables which cannot be changed anywhere in the code.
For this, we use the Const keyword after Private or Public like below,
Private Const Size As Int = 10
Public Const ItemNumber As Int = 100

Array of views / nodes (objects)


Views / nodes or objects can also be in an Array. The following code shows an example:

In B4A user interface objects are called views.


In the example below the Buttons are added to the parent view / node by code.

Sub Globals
Private Buttons(6) As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)


Private i As Int
For i = 0 To 5
Buttons(i).Initialize("Buttons")
Activity.AddView(Buttons(i), 10dip, 10dip + i * 60dip, 150dip, 50dip)
Buttons(i).Tag = i + 1
Buttons(i).Text = "Test " & (i + 1)
Next
End Sub

Sub Buttons_Click
Private btn As Button
btn = Sender
Log("Button " & btn.Tag & " clicked")
End Sub

Type variables
Type cannot be private. Once declared it is available everywhere (similar to Class
modules).
The best place to declare them is in the Process_Globals routine in the Main module.
Let us reuse the example with the data of a person.
Instead of declaring each parameter separately, we can define a personal type variable with
the Type keyword:

Public NbUsers = 10 As Int


Type Person(LastName As String, FirstName As String. Address As String, City As String)
Rasure B. BPage
From Google
Mobile Application Development

Public User(NbUsers) As Person


Public CurrentUser As Person

The new personal type is Person , then we declare either single variables or arrays of this
personal type.

To access a particular item use following code.

CurrentUser.FirstName
CurrentUser.LastName
User(1).LastName
User(1).FirstName

The variable name, followed by a dot and the desired parameter.


If the variable is an array then the name is followed by the desired index between brackets.
It is possible to assign a typed variable to another variable of the same type, as shown
below.
CurrentUser = User(1)

Casting
B4X 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 references 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.

Sub Globals
Private 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, 10dip, 10dip, 200dip, 50dip)
Activity.AddView(Btn2, 10dip, 70dip, 200dip, 50dip)
Activity.AddView(Btn3, 10dip, 130dip, 200dip, 50dip)
End Sub

Sub Btn_Click
Private btn As Button
btn = Sender ' Cast the Object to Button
btn.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub

The above code could also be written more elegantly:


Sub Globals

End Sub
Sub Activity_Create(FirstTime As Boolean)
Rasure B. BPage
From Google
Mobile Application Development

Private i As Int
For i = 0 To 9 ' create 10 Buttons
Private Btn As Button
Btn.Initialize("Btn")
Activity.AddView(Btn, 10dip, 10dip + 60dip * i, 200dip, 50dip)
Next
End Sub

Sub Btn_Click
Private btn As Button
btn = Sender ' Cast the Object to Button
btn.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub

Scope
Process variables
These variables live as long as the process lives.
You should declare these variables inside Sub Process_Globals.
This sub is called once when the process starts (this is true for all modules, not just the
main module).
These variables are the only "public" variables.

Which means that they can be accessed from other modules as well.
However, in B4A, not all types of objects can be declared as process variables.

For example, views / nodes cannot be declared as process variables.


The reason is that we do not want to hold a reference to objects that should be destroyed
together with the activity.
In other words, once the activity is being destroyed, all of the views which are contained in
the activity are being destroyed as well.
If we hold a reference to a view, the garbage collector would not be able to free the resource
and we will have a memory leak. The compiler enforces this requirement.
To access process global variables in other modules than the module where they were
declared their names must have the module name they were declared as a prefix.

Example:
Variable defined in a module with the name : MyModule

Sub Process_Globals
Public MyVar As String
End Sub

Accessing the variable in MyModule module:


MyVar = "Text"
Accessing the variable in any other module:
MyModule.MyVar = "Text"
Variables can be declared with:

Dim MyVar As String


In this case the variable is public same as Public.

Rasure B. BPage
From Google
Mobile Application Development

It is good practice to declare the variables like this:

Public MyVar As String

This variable is public.


It is possible to declare private variables in Sub Process_Globals like this:

Private MyVar As String


The variable is private to the activity or the module where it is declared.
For Activities it is better to declare them in Sub Globals.
For variables declared in Class modules in Sub Class_Globals the same rules as above are
valid.

Public MyVarPublic As String ' public


Private MyVarPublic As String ' private

Dim MyVar As String ' public like Public


Using Dim in Sub Class_Globals is not recommended !

Activity variables
These variables are contained by the activity.
You should declare these variables inside Sub Globals.
These variables are "private" and can only be accessed from the current activity module.
All object types can be declared as activity variables.
Every time the activity is created, Sub Globals is called (before Activity_Create).
These variables exist as long as the activity exists

Local variables
Variables declared in a subroutine are local to this subroutine.
They are "private" and can only be accessed from within the subroutine where they were
declared.
All objects types can be declared as local variables.
At each call of the subroutine the local variables are initialized to their default value or to
any other value you have defined in the code and are 'destroyed' when the subroutine is
exited.

Tips
A view / node can be assigned to a variable so you can easily change the common
properties of the view.

For example, the following code disables all views that are direct children of a Panel / Pane:

For i = 0 To MyPanel.NumberOfViews - 1
Private v As View
v = MyPanel.GetView(i)
v.Enabled = False
Next
If we only want to disable buttons:
For i = 0 To MyPanel.NumberOfViews - 1

Rasure B. BPage
From Google
Mobile Application Development

Private v As View
v = MyPanel.GetView(i)
If v Is Button Then ' check whether it is a Button
v.Enabled = False
End If
Next

***************************END**************************

Rasure B. BPage
From Google

You might also like