Professional Documents
Culture Documents
B4a Tutorijal
B4a Tutorijal
Main contributors :
Erel Uziel
Klaus Christl
nfordbscndrd
1 Getting started 7 Basic4Android Beginner's Guide
1 Getting started
Basic4android is a simple yet powerful development environment that targets Android devices.
Basic4android language is similar to Visual Basic language with additional support for objects.
Basic4android compiled applications are native Android applications, there are no extra runtimes or
dependencies.
Unlike other IDEs Basic4android is 100% focused on Android development.
Basic4android includes a powerful GUI designer with built-in support for multiple screens and
orientations. No XML writing is required.
You can develop and debug with the Android emulator or with a real device
(USB connected or over the local network).
Basic4android has a rich set of libraries that make it easy to develop advanced applications.
This includes: SQL databases, GPS, Serial ports (Bluetooth), Camera, XML parsing, Web services
(HTTP), Services (background tasks), JSON, Animations, Network (TCP and UDP), Text To Speech
(TTS), Voice Recognition, WebView, AdMob (ads), Charts, OpenGL, Graphics and more.
Android 1.6 and above are supported (including tablets like Motorola Xoom).
Installation instructions:
The first step should be to install the Java JDK as Android SDK requires it as well.
Note that there is no problem with having several versions of Java installed on the same computer.
- Install the SDK. The SDK doesn't always behave properly when it is installed in a path with
spaces (like Program Files). It is recommended to install it to a custom folder similar to
C:\Android.
- You should now install the platform tools and at least one platform image. You can use API 8 or
above. It is recommended to use API 8.
You can also install Google USB Driver if you need to connect a real device with USB.
1 Getting started 8 Basic4Android Beginner's Guide
- Open Basic4android.
On Windows 64 bit, Java will probably be installed under C:\Program Files (x86).
Common errors
- Windows XP - "Basic4Android.exe Application could not be initialised correctly error
0xc0000135" on startup. Basic4android requires .Net Framework 2.0 or above. Windows XP users
who didn't install it before should first install the framework.
- "javac: target release 1.5 conflicts with default source release 1.7" - Currently Basic4android
requires Java 6. It will not work with Java 7. Both versions can be installed on the same computer.
1.2 Installing Android Emulator 10 Basic4Android Beginner's Guide
Please follow the installation (and configuration) instructions if you have not done it yet:
http://www.basic4ppc.com/forum/basic...droid-sdk.html.
In this chapter, we will create a new AVD (Android Virtual Device) which is an emulator instance.
Then we will create a simple program that displays a simple message box and writes a message to
the log.
You can also connect a real device to the IDE:
Connecting your device with ADB
Connecting your device with B4A-Bridge
- Run Basic4android.
- The SDK Manager may appear depending on the version and configuration. You should choose
Tools - Manage AVDs.
1.2 Installing Android Emulator 11 Basic4Android Beginner's Guide
- Click on and fill the fields similar to the following image(it is recommended to choose
HVGA):
- Click on .
- You will see several windows popping up and disappearing. This is fine.
1.2 Installing Android Emulator 13 Basic4Android Beginner's Guide
Wait... on the first time it can take several minutes until the emulator is ready.
1.2 Installing Android Emulator 14 Basic4Android Beginner's Guide
We will design the layout of the user interface with the Designer on the Emulator and go step by
step through the whole process.
2 My first program 16 Basic4Android Beginner's Guide
You must save the project before you can run the Designer.
Click on
Wait until the Emulator is ready, this will take quite some time.
The label appears in the Emulator, and its default parameters are listed in the Designer.
We have now:
We need a second label similar to the first one. Instead of adding a new one, we copy the first one
with the same parameters. Only the Name, Left and Top parameters will change.
2 My first program 22 Basic4Android Beginner's Guide
Let us position the new Label and change its name to lblNumber2.
Let us now add a 3rd Label for the math sign. We copy once again lblNumber1.
Click on lblNumber1 in the Emulator, and in the Designer click in the 'Tools' menu on 'Duplicate
Selected View'.
Position it between the two first Labels and change its name to lblMathSign and its Text parameter
to '+'.
2 My first program 23 Basic4Android Beginner's Guide
Position it below the three Labels and change its name to edtResult. 'edt' for EditText and 'Result'
for its purpose.
Horizontal Alignment to
CENTER_HORIZONTAL
Text Size to 30
Let us add the Button to confirm the result or to generate a new calculation.
Position it below the EditText view; resize it and change following parameters:
Name: to 'btnAction'
Let us add the last Label for the comments, position it below the Button and resize it.
Horizontal Alignment:
CENTER_HORIZONTAL
Text Color to Black
Color to White
Alpha to 255
Click on .
To write the routines for the project we need to reference the views in the code.
This can be done with the Generate Members tool in the Designer.
2 My first program 27 Basic4Android Beginner's Guide
The Generate Members tool allows to automatically generate references and subroutine frames.
Clicking on en event of a view generates the Sub frame for this event.
First, we need to load our layout file to the Activity in the Activity_Create Sub.
- Enter 'Activity'
- Enter a dot
- The autocomplete function shows automatically all the possible parameters of the view.
- Enter 'L' , the autocomplete function shows the parameters beginning with 'L'
- Press the down arrow key, LoadLayout will appear with the online help for the given parameter or
method.
2 My first program 29 Basic4Android Beginner's Guide
- Enter '(', the online help is displayed showing the needed parameters for the method.
- Enter '"Main")'
We want to generate a new problem directly when the program starts. Therefore, we add a call to
the New subroutine.
To generate a new problem, that means generate two random numbers Number1 and Number2
between 1 and 9 and show them in the lblNumber1 and lblNumber2 Labels.
Rnd(1, 10) Random number generator, '1' min. number inclusive and '10' max. number exclusive.
lblComments.Text = "Enter the result" & CRLF & "and click on OK"
Displays the comment in lblComments. CRLF is the LineFeed character.
2 My first program 30 Basic4Android Beginner's Guide
If btnAction.Text = "O K" Then checks if the Button text equals "O K"
If yes then we check if the EditText is empty.
If yes, we display a MessageBox telling the user that there is no result in the EditText view.
If no, we check if the result is correct or if it is false.
If no then we generate a new problem, set the Button text to "O K" and clear the EditText view.
We have not yet set the package name so the IDE asks for it. Enter B4A.MyFirstProgram.
Click on .
Click on .
These two parameters can also be changed in the IDE in the Project menu.
When you see 'Completed successfully.' in above message box, the compiling and transfer is
finished.
Look at the emulator, you should see something similar to the image below, with different numbers.
2 My first program 32 Basic4Android Beginner's Guide
Create a new folder SecondProgram. Copy the all the files and folders from MyFirstProgram to the
new SecondProgram folder and rename the program file MyFirstProgram.b4a to
SecondProgram.b4a .
Click on .
Click on .
3 Second program 34 Basic4Android Beginner's Guide
Click on
Duplicate it
3 Second program 35 Basic4Android Beginner's Guide
Name to lblResult
Corner Radius to 5
Color to White
Alpha to 255
3 Second program 36 Basic4Android Beginner's Guide
Click on
Click on
to add a new button.
Name to btn0
Event name to btnEvent
Left to 10
Top to 120
Width to 55
Height to 55
Tag to 0
Text to 0
Size to 24
Click on StatelistDrawable.
Click on GradientDrawable
3 Second program 39 Basic4Android Beginner's Guide
Orientation to TOP_BOTTOM
First Color
Second Color
Orientation to TOP_BOTTOM
First Color
Second Color
Name to btn1
Tag to 1
Text to 1
Click on Find(F3)
3 Second program 42 Basic4Android Beginner's Guide
Click on
Click on and .
Now we write the routine, that handles the Click events of the Buttons.
The Event Name for all buttons, excepted btnAction, is "btnEvent".
The routine name will become btnEvent_Click, let us enter following code:
We need to know what button raised the event. For this, we use the Sender object which is a special
object that holds the object reference of the view that generated the event in the event routine.
The "&" character means concatenation, so we just append to the already existing text the Tag value
of the button that raised the event.
When clicking on the BS button we must remove the last character from the existing text in
lblResult.
However, this is only valid if the length of the text is bigger than 0. This is checked with:
If lblResult.Text.Length >0 Then
We can try to improve the user interface of the program in adding some colors to the lblComments
Label.
Let us set:
- Yellow for a new problem
- Light Green for a GOOD answer
- Light Red for a WRONG answer.
Let us first modify the New routine, where we add line 55.
Another improvement would be to hide the '0' button to avoid entering a leading '0'.
For this, we hide the button in the New subroutine in line 57.
In addition, in the btnEvent_Click subroutine, we hide the button if the length of the text in
lblResult is equal to zero and show it if the length is higher than zero, lines 85 to 89.
As we are accessing btn0 in the code we need to declare it in the Globals routine.
4 The IDE
The Integrated Development Environment.
When you run the IDE you will get a form like the image below:
Example: SecondProgram.b4a.
4 The IDE 47 Basic4Android Beginner's Guide
4.1.1 Toolbar
Debugging
Activity properties
Orientations supported
Both modes.
Portrait only.
Landscape only.
4 The IDE 50 Basic4Android Beginner's Guide
Configure Paths
Word wrap
With word wrap. The end of the line is wrapped to the next line.
Auto Save
Take Screenshot
Clicking on
Clean Project Deletes all generated the files that are generated during compilation.
4 The IDE / 4.2 Code area 52 Basic4Android Beginner's Guide
Hovering with the mouse over the collapsed routine name shows its content.
4 The IDE / 4.2 Code area 53 Basic4Android Beginner's Guide
Example:
Then you can add the subroutines between the two limits:
Then clicking on
shows the beginning of the code, not all the routines in the region.
4 The IDE / 4.2 Code area 54 Basic4Android Beginner's Guide
A selected part of the code can be set to comment lines or set to normal.
Original code
Click on .
4.2.6 Bookmarks
You can set 'bookmarks' everywhere in the code and jump forward and backwards between these
bookmarks.
Click on .
4.2.7 Indentation
Example with an
indentation of 4
Original code
Click on .
4.2.8 Autocomplete
Press Tab.
When selecting a word, this one is highlighted in dark blue and all the occurences in the code are
highlighted in light blue and in the scrollview on the right side.
With the slider you can move up or down the code to go to the other occurences.
4.2.11 Debugging
If this option is checked then the compiled code will contain debugging code.
The debugging code allows the IDE to connect to the program and inspect it while it runs.
When the program starts, it will wait for up to 10 seconds for the IDE to connect. Usually the IDE
will connect immediately. However if you run your program manually from the phone you will see
it waiting.
The name of the compiled APK file will end with _DEBUG.apk. You should not distribute this apk
file as it contains the debugging code which adds a significant overhead.
Another relevant option in this menu is Include Debug Information. This option doesn't have any
effect when the Attach Debugger option is checked.
When Attach Debugger is not checked (which means that debugging code will not be added) this
option determines whether the original B4A code will be added to the compiled APK file. Adding
B4A code is useful for one specific reason. During an exception the message will include the
original B4A line and not just the Java line.
When we run the program with Attach Debugger checked, the IDE will open the debugger module
at the bottom of the screen:
Breakpoints - You can mark lines of codes as breakpoints. This is done by pressing on the grey area
left of the line.
The program will pause when it reaches a breakpoint and will allow you to inspect the current state.
Logging - The Logs tab at the right pane is very useful. It shows messages related to the
components life cycle and it can also show messages that are printed with the Log keyword. You
should press on the Connect button to connect to the device logs. Note that there is a Filter
checkbox. When it is checked you will only see messages related to your program. When it is
unchecked you will see all the messages running in the system. If you are encountering an error and
do not see any relevant message in the log, it is worth unchecking the filter option and looking for
an error message.
Note that the log is maintained by the device. When you connect to a device you will also see
previous messages.
4 The IDE / 4.2 Code area 64 Basic4Android Beginner's Guide
4.2.12 Breakpoints
Clicking on a line in the left margin adds a breakpoint. When the program is running it stops
running at the first breakpoint.
Run the program, the program stops at the breakpoint and the IDE looks like below. The breakpoint
line is highlighted in yellow.
.
At the bottom of the IDE you find other information.
Debugger is connected.
Double click to detach the Debuger.
Global variables.
Examples:
btnAction: Type = Button Left = 190 Top = 0 Width = 115 Height = 55 Tag = empty Text = OK
Number1 = 6
Local variables.
Hovering with the mouse over a view shows its parameters like in the list.
4 The IDE / 4.2 Code area 66 Basic4Android Beginner's Guide
Click on F8.
The program executes the next code line.
Click on F8.
The program executes the next code line.
4.3 Tabs
There are 4 tabs at the bottom right corner of the IDE that
displays the followin information.
Module list
Clicking on a module shows its code in the code area.
4.3.2 Files
This window lists all the files that have been added to the project.
These files are saved in the Files.DirAssets folder.
These can be any kind of files: layouts, images, texts, etc.
button.
Clicking on this button removes the selected files from the
list and from the Files folder of the project.
Make shure to have a copy of the files you remove, because they are removed from the Files
folder, but not transfered to the recycle bin, that meas they are definitively lost if you don't
have a copy.
4.3.3 Logs
We add the two lines 51 and 53 in the program 'SecondProgram' in the 'New' routine.
When it is checked you will only see messages related to your program. When it is
unchecked you will see all the messages running in the system. If you are encountering an error and
do not see any relevant message in the log, it is worth unchecking the filter option and looking for
an error message
If the debugger is still running, select Debug > Stop from the IDE menu, press F11 or click on
4.3.4 Libs
In cases 1) and 2) the physical sizes of the screens are the same but the density of the pixels is
different.
In cases 1) and 3) the densities are the same but the physical dimensions of the screen in case 3)
are the double of those of the screen in case 1) giving a surface 4 times bigger.
Let us look at the size of a button with 80 / 80 dip, its physical size.
dips pixels inch
1) 80 80 0.5
2) 80 120 0.5
2) -- 80 0.375 dimension given in pixels not in dips
3) 80 80 0.5
It is possible to generate special Emulators with special sizes, resolutions and densities.
5 Screen sizes and resolutions 72 Basic4Android Beginner's Guide
A same layout file can fit into different screen resolutions, but with some restrictions.
We will use the TestLayouts program to test the same layout with different screen resolutions.
The source code is in the <Guide>\SourceCode\TestLayouts directory.
If you do not have these emulators, you must create them in the AVD
Manager. Look here to generate an Emulator.
Tests with the three Emulators with different resolutions and different densities.
The image sizes are reduced by a factor of 0.5 for easier comparison.
What we see:
- with the standard resolution, the image in the emulator is equal to the original layout.
- with the 240/320 resolution we see that there are the 'expected' 40 pixels missing.
- with the 480/800 resolution, we see that there are the 'expected' 80 extra pixel.
The numbers of items in the ListView are the same for all three resolutions.
5 Screen sizes and resolutions 74 Basic4Android Beginner's Guide
In line 23 we calculate the top of the pnlToolBox panel according to the screen height.
In line 24 we calculate the ListView height according to the top of the pnlToolBox.
What we see:
- with the standard resolution, the image in the emulator is still equal to the original layout.
- with the 240/320 resolution we see that the buttons are at the bottom of the screen but the
ListView height is shortened.
- with the 480/800 resolution we see that the buttons are at the bottom and the ListView is
higher.
The numbers of items in the ListView are different in the three layouts because the ListView height
has been adapted to the different relative screen heights.
In the first test, the number of items in the ListView were the same !
These examples show that it is not easy to have one layout for different screen resolutions.
In the example above it was relatively easy because the view in the middle is easily adjustable.
5 Screen sizes and resolutions 75 Basic4Android Beginner's Guide
Even when we load the layout file in the three emulators with resolutions 480 / 800, 320 / 480 and
240 / 320 pixels the layout is stretched or shrinked according to the screen size, but we see of course
also the extra and missing pixels depending on the different relative screen heights.
The Android OS autoscale system adjusts the Left, Top, Width, Height, FontSize and other
parameters with the scale factor but does NOT resize the vertical positions nor the heights of the
views proportional to the screen height. The same is valid for the width in landscape mode.
5 Screen sizes and resolutions 76 Basic4Android Beginner's Guide
There are special functions to accomode different screen sizes and resolution.
DipToCurrent calculates a dimension with the given Length according to the scale of the current
device.
The 'standard' resolution is 160 dpi (dots per inch) and sacle 1.
No spaces between the number and dip!
If we have a Button with a dimension of 50 * 50 pixels standard scale, to its dimensions we should
set Button1.Width = 50dip and Button1.Height = 50dip.
With a scale of on the Butoon dimension will be:
Scale Pixels
1 50 * 50
1.5 75 * 75
Example:
Dim Button1 As Button
Button1.Initialize("Button1")
Activity.AddView(Button1, 20%x, 30%y, 100dip, 50dip)
The values for the Left, Top, Width and Height properties in the Designer are considered as
dip values.
6 The Emulator 77 Basic4Android Beginner's Guide
6 The Emulator
The Emulator or Virtual Device is a program that simulates devices on the PC.
To launch an Emulator click in the IDE in the Tools menu on Run AVD Manager.
.
Click on
6 The Emulator 78 Basic4Android Beginner's Guide
Wait until the Emulator is ready, this will take quite some time.
6 The Emulator 79 Basic4Android Beginner's Guide
Let us add a new Emulator with a resolution of 480 / 800 pixels, density 240.
Click on
Enter 16.
Click on
Click on .
6 The Emulator 80 Basic4Android Beginner's Guide
Click on .
Click on .
When you either run the program or connect the Emulator from the Designer, sometimes you will
see the message below.
But, even after having clicked on continue, sometimes you will see this message.
Run the program once more, in most cases the Emulator will be connected and work well.
This often happens when the Emulator is still running a program or if the Emulator is still
connected to another project. In this case press the back button until you reach the Emulator's home
screen, and try again.
If this happens, a second time, close the current Emulator and run it again from the AVD Manager.
If the first message above appears too often you can increase the process timeout value.
6 The Emulator 82 Basic4Android Beginner's Guide
7 B4A Bridge
Up until now there were two methods for testing your application during development.
You can either work with the Android emulator or if your device supports ADB debugging, you
were able to connect to your real device.
The Android emulator is very slow compared to a real device (especially with applications
installation).
However not all devices support ADB debugging. This is exactly the reason for the new B4A-
Bridge tool.
B4A-Bridge is made of two components. One component runs on the device and allows the second
component which is part of the IDE to connect and communicate with the device.
The connection is done over a network (B4A-Bridge cannot work if there is no network available).
Once connected, B4A-Bridge supports all of the IDE features which include: installing applications,
viewing LogCat and the visual designer.
Android doesn't allow applications to quietly install other applications, therefore when you run your
application using B4A-Bridge you will see a dialog asking for your approval.
The status bar at the bottom of the screen shows the current status:
That's it.
When B4A-Bridge gets connected it first checks if the designer application needs to be updated. In
that case it will first install the designer application.
B4A-Bridge keeps running as a service until you press on the Stop button.
You can always reach it by opening the notifications screen:
As mentioned above, when you run an application you are required to approve the installation. You
will usually see the following screens:
7 B4A Bridge 85 Basic4Android Beginner's Guide
In the above dialog you should choose Open to start the application.
If you try to install an existing application signed with a different key, the install will fail (without
any meaningful message). You should first uninstall the existing application. Go to the home screen
- Settings - Applications - Manage applications - choose the application - Uninstall.
Once you finished developing you should press on the Stop button in order to save battery.
Note that B4A-Bridge was written with Basic4android.
The source code is available here: http://www.basic4ppc.com/forum/basic...html#post45854
8 The Designer 86 Basic4Android Beginner's Guide
8 The Designer
The Designer allows generating layouts with either the Emulator or a real device.
8 The Designer / 8.1 The menu 87 Basic4Android Beginner's Guide
This menu allows you to select the view you want to add on the
current layout on the device or the Emulator.
8.2 Tools
Clicking on en event of a view generates the Sub frame for this event.
Click on
to bring the selected view to front.
Click on
to remove it.
The grid is an invisible grid with a given size. The default grid size is 10 pixels. That means that all
positions and dimensions of a view will be set to values in steps corresponding to the grid size.
Moving a view will be done in steps equal to the grid size.
Click on
If different devices or Emulators are connected, you will be asked what device or Emulator you
want to connect.
Click on to confirm.
When the View combo box is selected, pressing the Up or Down arrows will move through the
views, and the properties for the view will display automatically.
and click on .
8 The Designer / 8.5 Parameter list 94 Basic4Android Beginner's Guide
Name Name of the view. It is good practice to give meaningful names. Common
usage is to give a 3 character prefix and add the purpose of the view. In the example, the view is of
type Label and its purpose is to enter a result. So we give it the name "lblResult", "lbl" for
Label and "Result" for the purpose. This does not take much time during the design of the layout
but saves a lot time during coding and maintenance of the program.
Type Type of the view, not editable. It is not possible to change the type of a view.
If you need to, you must remove the view and add a new one.
Event Name Generic name for the subroutines that manages the view's events. By default,
the Event Name is the same as the view's name like in the example. The Events of several Views
can be redirected to a same subroutine. In that case you must enter the name of that routine.
Look at the SecondProgram example for the Click event management for the buttons of the
keyboard, the btnEvent_Click routine.
8 The Designer / 8.5 Parameter list 95 Basic4Android Beginner's Guide
Parent Name of the parent view. Activity, in the example. The parent view can be
changed in selecting the new one in the list.
Left X coordinate of the left edge of the View from the left edge of its parent
View, in pixels (the pixels are in reality dips, density independent pixels).
Top Y coordinate of the upper edge of the View from the upper edge of its parent
View, in pixels (the pixels are in reality dips, density independent pixels).
Width Width of the View in pixels (the pixels are in reality dips, density
independent pixels).
Height Height of the View in pixels (the pixels are in reality dips, density
independent pixels).
Enabled Enables or disables the use of the View Ex: Enabled = True
Tag This is a place holder which can used to store additional data. Tag can simply
be text but can also be any other kind of object. Tag is used in the SecondProgram example for the
numeric buttons click events management in the btnEvent_Click routine.
8 The Designer / 8.6 Layout variants 96 Basic4Android Beginner's Guide
Select:
480 x 320
scale = 1
Click on
Button height 65
ListView1:
Width = 380
Height = 220
8 The Designer / 8.6 Layout variants 99 Basic4Android Beginner's Guide
to
We can achieve a similar effect in the Designer when a different Layout Variant is selected and we
switch to Landscape mode (Ctrl-F11).
8 The Designer / 8.8 Adding views by code 101 Basic4Android Beginner's Guide
The Abstract Designer is a tool that shows the layout in a separate window and is part of the
Designer. It is much faster than the Emulator.
Its main purpose is to create different layout variants.
The different views are not shown with their exact shape but only as coloured rectangles.
Clicking on a view shows its properties in the Designer.
Layout
Matches :
The chosen variant in the
Designer.
The connected device.
Zoom
Two possibilities:
50%
100%
Tools
8.7.2 Example
Let us take a simple example with a layout in portrait mode, like the image below.
It is also possible to add views by code instead of using the Designer with a device, the Emulator or
the Abstract Designer.
Advantage : you have full control of the view.
Disadvantage : you have to define almost everything.
For the positions and dimensions of the views on the screen two special writings are available:
dip density independent pixels.
100dip = DipToCurrent(100) DipToCurrent is a Keyword dip is the Shortcut
100dip = 100 / 160 * device density
The default density is 160 dpi dots per inch (pixels per inch)
Densities in Android:
o 120 scale 0.75
o 160 scale 1 default
o 240 scale 1.5
o 320 scale 2
%x and %y represent distances proportional to the active screen width and height.
20%x = 0.2 * Activity.Width
90%y = 0.9 * Activity.Height
20%x = PerXToCurrent(20) PerXToCurrent is a Keyword %x is the Shortcut
90%y = PerYToCurrent(90)
Example:
Let us put a Label on top of the screen and a Panel below it with a Label and a Button on it:
13 SQLite Database 107 Basic4Android Beginner's Guide
If the Label had been added in the Designer, all the above code wouldn't have been necessary
because the properties would already have been defined in the Designer.
In the Activity.AddView line we see that:
the Left property is set to 20%x, 20% of Activity.Width.
the Top property is set to 10dip, 10 density independent pixels.
the Width property is set to 60%x, 60% of Activity.Width
the Height property is set to 30dip, 30 density independent pixels.
lblPanelTitle.Initialize("")
lblPanelTitle.Color = Colors.Red
lblPanelTitle.TextSize = 16
lblPanelTitle.TextColor = Colors.Blue
lblPanelTitle.Gravity = Gravity.CENTER_HORIZONTAL + Gravity.CENTER_VERTICAL
lblPanelTitle.Text = "Panel test"
A process starts when the user launches your application, assuming that it is not running already in
the background.
The process end is less determinant. It will happen sometime after the user or system has closed all
the activities.
If for example you have one activity and the user pressed on the back key, the activity gets closed.
Later when the phone gets low on memory (and eventually it will happen) the process will quit.
If the user launches your program again and the process was not killed then the same process will
be reused.
A Basic4android application is made of one or more activities. Android support several other
"main" components. These will be added to Basic4android in the future.
One major difference is that, while an activity is not in the foreground it can be killed in order to
preserve memory. Usually you will want to save the state of the activity before it gets lost. Either in
a persistent storage or in memory that is associated with the process.
Later this activity will be recreated when needed.
Another delicate point happens when there is a major configuration change in the device. The most
common is an orientation change (user rotates the device). When such a change occurs the current
activities are destroyed and then recreated. Now when we create the activity we can create it
according to the new configuration (for example, we now know the new screen dimensions).
9 Process and Activity life cycle 110 Basic4Android Beginner's Guide
When you create a new activity you will start with the following code template:
Variables can be either global or local. Local variables are variables that are declared inside a sub
other than Process_Globals or Globals.
Local variables are local to the containing sub. Once the sub ends, these variables no longer exist.
Global variables can be accessed from all subs.
Process variables
Activity variables
To summarize, you can test whether FirstTime is True and then initialize the process variables that
are declared in Sub Process_Globals.
9 Process and Activity life cycle 112 Basic4Android Beginner's Guide
Each time the activity moves from the foreground to the background Activity_Pause is called.
Activity_Pause is also called when the activity is in the foreground and a configuration change
occurs (which leads to the activity getting paused and then destroyed).
Activity_Pause is the last place to save important information.
Generally there are two types of mechanisms that allow you to save the activity state.
Information that is only relevant to the current application instance can be stored in one or more
process variables.
Other information should be stored in a persistent storage (file or database).
For example, if the user changed some settings you should save the changes to a persistent storage
at this point. Otherwise the changes may be lost.
Activity_Resume is called right after Activity_Create finishes or after resuming a paused activity
(activity moved to the background and now it returns to the foreground).
Note that when you open a different activity (by calling StartActivity), the current activity is first
paused and then the other activity will be created if needed and (always) resumed.
As discussed above Activity_Pause is called every time that the activity moves from the foreground
to the background. This can happen because:
1. A different activity was started.
2. The Home button was pressed.
3. A configuration changed event was raised (orientation changed for example).
4. The Back button was pressed.
In scenarios 1 and 2, the activity will be paused and for now kept in memory as it is expected to be
reused later.
In scenario 3 the activity will be paused, destroyed and then created (and resumed) again.
In scenario 4 the activity will be paused and destroyed. Pressing on the Back button is similar to
closing the activity. In this case you do not need to save any instance specific information (the
position of pacman in a PacMan game for example).
The UserClosed parameter will be true in this scenario and false in all other. Note that it will also be
true when you call Activity.Finish. This method pauses and destroys the current activity, similar to
the Back button.
You can use UserClosed parameter to decide which data to save and also whether to reset any
related process variables to their initial state (move pacman position to the center if the position is a
process variable).
10 Variables and objects 113 Basic4Android Beginner's Guide
Primitive types are always passed by value to other subs or when assigned to other variables.
For example:
The variable A = 12
It's passed by value to routine S2
Variable A still equals 12, even though B was changed in routine S2.
Variable B = 12
Its value is changed to B = 45
10 Variables and objects 114 Basic4Android Beginner's Guide
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.
For Views 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
Variables are declared with the Dim keyword followed by the variable name the As keyword and
followed by the variable type. Examples:
The names of the variables separated by commas and followed by the type declaration.
View names must be declared when we want to use them in the code.
If we want, for example, change the text in an EditText view in the code, like
edtCapital.Text = "1200",
we need to reference this EditText view by its name edtCapital, this is done with the Dim
declaration.
If we never make any reference to this EditText 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.
Arrays are collections of data or objects that can be selected by indices. Arrays can have multiple
dimensions.
The declaration contains the Dim keyword followed by the variable name LastName, the number of
items between brackets (50), the keyword As and the variable type String.
Examples:
The last index is equal to the number of items in each dimension minus 1.
LastName(49), Matrix(2,2), Data(2,4,9)
10 Variables and objects 116 Basic4Android Beginner's Guide
or
We declare the variable Dim NbPers As Int and set its value to 10, NbPers = 10 .
The colon ":" is a separator for two statement on the same line.
Then we declare the arrays with this variable instead of the number 10 as before.
The big advantage is that, if we need one time to change the number of items, we change only ONE
value.
In the example below the Buttons are added to the Activity by code.
The Buttons could also have been added in a layout file, in that case they must not be initialized nor
added to the Activity and the Text and Tag properties should also be set in the Designer.
In that case the code would look like this:
10 Variables and objects 118 Basic4Android Beginner's Guide
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
It is possible to assign a typed variable to another variable of the same type, as shown below.
10 Variables and objects 119 Basic4Android Beginner's Guide
10.4 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 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.
10.5 Scope
10.6 Tips
A view 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 the activity:
11 Modules
There does exist at least one module, the main module.
Its name is always Main and cannot be changed.
Each Activity has its own module. For a better knowledge of Activity life cycle have a look at the
Process and Activity life cycle chapter.
To access any object or variable in a module other than then module where they were declared you
must add the module name as a prefix to the object or variable name separated by a dot.
To access these variables from another module the name is Main.Value1 or Main.Value2.
It is NOT possible to access any view from another activity module, because when a new activity is
started the current activity is paused and no more accessible !
11 Modules 124 Basic4Android Beginner's Guide
12 Example programs
Let us make three different user interfaces to select three different screens.
For each of the three pages there is a layout file Page1, Page2 and Page3.
Each layout file is loaded to a Panel or a TabHost panel.
These layouts can contain whatever views you need.
12 Example programs 127 Basic4Android Beginner's Guide
We have:
- 3 pages, each one in it's own Activity.
- 3 process global variables, Value1, Value2 and Value3
- on each page 1 EditText view to modify the Value variable with page index.
- 2 Labels to display the two other variables.
- on Page1 a small red square Panel to move around.
We can:
- Change Value1 in Page1.
- Change Value2 in Page2.
- Change Value3 in Page3.
- Move the small red square over the screen.
- Select either Page2 or Page3 on Page1.
12.2 Three Activity example program 131 Basic4Android Beginner's Guide
For this we must create two new Modules: Page2 and Page3.
and click on .
Add now a new module "Page3" the same way as Page2 and modify the code like below:
When the routine is called the first time, we initialize the three Value variables.
12.2 Three Activity example program 134 Basic4Android Beginner's Guide
When the "Main" Activity is paused, due to either a page change or the program closing, we:
- set variable Value1 to the edtValue1.Text contend.
- save the Map to file Init.txt.
To go back to Page1 from either Page2 or Page3, the user must press the Back key. To avoid that
the program stops when the user clicks, by inadvertence, one time too much, we check in Sub
Activity_KeyPress what key was pressed. And if it's the Back key we display a message in a
MessageBox asking the user if he really wants to quit the program. If Yes, then we set the Return
value to False that means that the event is sent back to the OS to close the program. If the answer is
No, we set the Return value to True, that means that we 'consume' the event and the OS will not
stop the program.
12.2 Three Activity example program 135 Basic4Android Beginner's Guide
To show how to manage layout parameters we have the small red square, pnlMove, that can be
moved on the screen. The position of pnlMove is handled in Sub Activity_Touch where we get
three parameters:
- Action holding the value of the action the user made.
ACTION_DOWN the user touches the screen.
ACTION_MOVE the user moves on the screen
ACTION_UP the user leaves the screen
- X the X coordinate of the finger on the screen.
- Y the Y coordinate of the finger on the screen.
- when Action is equal to ACTION_MOVE the user moves his finger on the screen.
we calculate the relative displacement, dX and dY, in both directions and set the new Left
and Top parameters of pnlMove (lines 82 to 85).
In Sub btnPage_Click we start the Page Activity according to what button was pressed.
- We declare a new Button object, Send.
- We attribute Sender to Send .
Sender is the buttom view that raised the event.
- Depending on the Tag value of the sender object we start the correct Activity.
Main:
Page 1:
ScrollView is a very versatile view to display lists of objects holding data or user interface views.
ListViews are, currently, limited to two lines of text and an image per data set.
ScrollViews have an internal Panel, bigger than the screen, that can be scrolled vertically and holds
any type of views either as one layout or as lists of view sets.
Personally, I prefer working with variables rather than with values. The maintenance and
modification of a program is much easier with variables than with values.
12.3 Scrollview example program 140 Basic4Android Beginner's Guide
Then we read the csv file, fill the headers and the table (ScrollView).
First, if the headers do exist, we read the csv file with the headers.
Or, if the headers do not exist, we read the csv file without the headers and set default
header names Col1, Col2 etc.
Get the number of columns.
Display the headers SetHeader(h).
Display the table, by adding the different rows to the ScrollView AddRow(row).
12.3 Scrollview example program 143 Basic4Android Beginner's Guide
Note: an underscore character at the end of a line, like in line 212 means
'continue same instruction next line'.
12.3 Scrollview example program 145 Basic4Android Beginner's Guide
Other functions:
Cell_Click
Click event of one of the cells in the table.
o Dim rc as a RowCol variable and Dim l as a Label
o Set l equal to the Sender, the View that raised the event
o Set rc equal to the Sender Tag parameter
o Call the SelectRow routine
o Display in the Activities title the row and column indexes and the cell content.
Header_Click
Click event of one of the header cells in the table.
o Dim l as a Label and Dim col as an integer
o Set I equal to the Sender
o Set col equal to the Sender Tag parameter, which is the column index.
o Display the selected column in the Activity title.
12.3 Scrollview example program 146 Basic4Android Beginner's Guide
SelectRow
Routine managing the colors showing a selected row and cell.
It is called from the Cell_Click routine
o Dim col as an integer.
o If there is a row selected, set the normal cell color.
o Set the SelectedRow variable to the new selected row index..
o Set the selected row and selected cell colors.
12.3 Scrollview example program 147 Basic4Android Beginner's Guide
GetView
Gets the Label object for the given row and column.
o Dim l as a Label.
o Gets the View in the given row and column, the view index in the ScrollView panel
is equal to Row * NumberOfColumns + Col .
o Returns the Label.
GetCell
Gets the text of the Label for the given row and column.
o Gets the View in the given row and column.
o Return the Views Text parameter.
ClearAll
o Removes all Views (Labels) from the ScrollView Panel
o Sets the ScrollView Panel Height to 0
o Sets the select row index to -1, no row selected
12.3 Scrollview example program 148 Basic4Android Beginner's Guide
13 SQLite Database
The demonstration program is: SQLExample.b4a
The interface between your program and the database is a the SQL language.
The data is stored in tables, each table has a certain number of columns and rows.
Each row contains a data set and the different data of a given set are stored in the columns.
Database initialisation:
SQL1.Initialize(DBDirName, DBFileName, True)
DBDirName = Directory name of the database.
DBFileName = Database file name.
True = Create if necessary False don't create
13 SQLite Database 150 Basic4Android Beginner's Guide
Table creation:
CREATE TABLE TableName ( ID INTEGER PRIMARY KEY, Col1 TEXT, Col2 FLOAT )
Creates a table with the name 'TableName' and three columns:
Column Index Name Variable Type
1 ID INTEGER PRIMARY KEY
2 Col1 TEXT
3 Col2 FLOAT
Adding data:
Updating data:
Reading data:
The column to order can be given either by its name Col1 or its number 2.
The column numbering begins with 1.
13 SQLite Database 151 Basic4Android Beginner's Guide
Filtering
SELECT * FROM Tablename WHERE Col1 LIKE 'abc' AND Col2 LIKE 123
Cursor1 = SQL1.ExecuteQuery("SELECT * FROM TableName" WHERE Col1 LIKE
'abc%' AND Col2 LIKE 123 ")
The % character can be used as a wildcard:
abc means the exact sequence
%abc means beginning with any characters and ending with abc
abc% means beginning with abc and ending with any characters
%abc% means abc anywhere in the string
A single column
SELECT Col1 FROM TableName
Cursor1 = SQL1.ExecuteQuery("SELECT Col1 FROM TableName")
Max / min value in a column, in the examples the max and min values of the given column.
SELECT max(Col1) FROM Tablename
SELECT min(Col1) FROM Tablename
Cursor1 = SQL1.ExecuteQuery("SELECT max(Col1) FROM TableName")
Cursor1 = SQL1.ExecuteQuery("SELECT min(Col1) FROM TableName")
13 SQLite Database 152 Basic4Android Beginner's Guide
It is based on the Scrollview example program for the display of the database.
Clicking on a header sorts the database accoring to this column in ASC ascending mode.
13.2.1 Editing
Selecting a data set we get the screen below.
13.2.2 Filtering
If we change the AND parameter to OR. We get two more data sets.
Three persons with a first name of John OR living on a city beginning with Lon…
The active function is displayed in green.
It is good practice to add an additional column, called 'ID' with a unique number to differentiate the
data sets.
So the columns are: ID, FirstName, LastName, Address, City
Each column must be given a variable type: INTEGER, TEXT, FLOAT, BLOB .
In our database example we have following types:
ID INTEGER PRIMARY KEY
FirstName TEXT
LastName TEXT
Address TEXT
City TEXT
13 SQLite Database 157 Basic4Android Beginner's Guide
- First reference the SQL library in the tab in the lower right corner in the IDE.
- Define
o the file name : persons.db
o the directory name : File.DirInternal (File.DirRootExternal)
o the table name : persons
- Copy the default database from the DirAssets folder to the DBFileDir folder if it does exist and
initialize the database.
- Generate the Edit and the Filter View. The code below shows only the Edit View generation, the
code for the Filter View is similar.
Define the Label height LHeight, the EdidText height EHeight and the space THeight
between two following Labels.
In a loop for each colum:
o Dim, Initialize and add the Label view
o Set the ColumnName to the Label Text parameter
o Dim, Initialize and add the EditText view
o Set the EditText for the first colum to diabled, the ID value cannot be changed.
13 SQLite Database 159 Basic4Android Beginner's Guide
Without the filter, the query text could look like this:
SELECT * FROM persons ORDER BY ID ASC
Then we:
Execute the query and put the result in Cursor1
Dim the Col array variable.
Call the SetHeader routine to update the headers.
Set NumerOfRows to 0
For each row in the table
o Dim a new Col array variable
o Fill the Col array variable with the values of each data set
o Call the AddRow(Col) routine.
Close the Cursor
And set the Activities title to the DBFileName.
13 SQLite Database 161 Basic4Android Beginner's Guide
We
Dim the row array variable for the values of a row or data set
We fill the row array variable with the values of the Text paramter of the EditView views in
the Edit view. The index of the EditView is calculated with i * 2 + 1, the indexes are all
oss numbers. The views with even index numbers are the Labels.
We set UPDATE DBTableName Set ColumnName(0) = 'row(0)' and add the values for all
the other columns.
Add WHERE ColumnName(0) = 'value of column 0'
The query text could look like this:
UPDATE persons Set ID = '12', FirstName = 'Jules', LastName =
'VERNE', Address = 'Rue St.Honoré', City = 'Paris' WHERE ID = '12'
13 SQLite Database 162 Basic4Android Beginner's Guide
We Dim an array variable row, containing the values of the data set.
We Dim a new Cursor object
We get the max value of the ID column
we set SELECT max( ColumnName(0)) FROM DBTableName
equivalent to SELECT max(ID)FROM persons
and get row(0)
If there is at least one value missing we display an error message and leave the routine.
13 SQLite Database 163 Basic4Android Beginner's Guide
Then we call the AddRow(row) routine to add the new data set to the Scrollview.
And set the Edit button to visible if there is at least one data set in the database.
We calculate the new height hh of the inner panel of the scrollview and set it to the
scrollviews ScrollPosition.
We need to add a DoEvents keyword to force the height update.
13 SQLite Database 164 Basic4Android Beginner's Guide
Then we need to update the content of the labels in the rows of the table. That means put the
values of the Text parameters of the Lables in the row above the row to the Label in the row
to delete and so on.
A focus change in the EditText views of the Edit Panel or the Filter Panel, positions this
EditText view on top of the screen.
14 GPS
The GPS library has three objects:
GPS
GPSSatellite
Location
The example program will show several functions of the GPS library and has following functions.
Connecting the GPS
Getting and displaying GPS information
Saving a GPS path
Display the available satellites
Showing Google maps
Show a GPS path on the map
The GPSSatellite object holds various information about a GPS satellite. A List with the available
satellites is passed to the GpsSatus event.
Satellite data:
Azimuth 0 - 360 degrees
Elevation 0 - 90 degrees
Prn (Pseudo random number)
Snr (Signal / noise ratio)
UsedInFix True if the satellite is used to determine the curreent fix.
A Location object holds various information about a specific GPS fix (position).
In most cases you will work with locations that are passed to the GPS LocationChanged event.
The location object can also be used to calculate distance and bearing to other locations.
The GPS example program shows several possibilities of the GPS library and has following
functions :
Connect the GPS
Get and display GPS information
Save a GPS path
Display the available satellites
Display Google maps
Display a GPS path on the map
Setup Satellites
14 GPS 170 Basic4Android Beginner's Guide
Displays Google maps centerd on the default coordinates (defined in the setup).
If there is a GPS path, this one is displayed, centered and zoomed to show the whole path.
Activates the GPS and memorizes the fixes depending on the setup.
For certain functions, the button color is red when they are activated .
14.2.2 Setup
The setup screen allows to define setup parameters for the program.
GPS
- min time between two fixes.
- min distance between two fixes.
Enable display of:
- Speed
- Bearing
- Windrose
- Scale control
GPS display.
The minimum time and minimum distance to raise a fix change can be set in the setup screen.
Values of 0 for both parameters give the fastest aquisition frequency.
The number of memorized fixes is displayed in the titlebar.
The map can be displayed at the same time with the current GPS location.
After stopping the GPS the user is asked to save the path giving a file name and a comment.
14 GPS 174 Basic4Android Beginner's Guide
14.2.4 Satellites
The Satellites screen displays the information about the satellites currently received by the GPS.
The following elements can either be displayed or hidden, set in the Setup screen :
Type control MAP or SATELLITE
Scale control
Zoom control
GPS path (polyline)
Markers
14 GPS 176 Basic4Android Beginner's Guide
The data from the GPS can be memorized and saved in files.
The GPS path screen shows the data of the selected GPS path.
The data can be scrolled verticaly, normal ScrollView scrolling, and horizontaly with the slider.
The left column with the ID remains always visible.
14 GPS 178 Basic4Android Beginner's Guide
You can:
Filter a path
Clicking on one of the headers below changes the unit of the displayed values.
check / uncheck
Clicking on a marker cell changes between checked and unchecked. Marker
14 GPS 179 Basic4Android Beginner's Guide
When memorizing GPS paths it often happens that there are some point aligned along a straight
line. These points can be removed.
The principle of the program is the following.
The program looks at 3 successive points.
Calculates the distance of the midpoint out of the line between the the two outer points.
If this distance is higher than the predefined value the point is selected and can be deleted.
Enter a comment.
KML documentation.
14 GPS 181 Basic4Android Beginner's Guide
Not all the code of the program will be explained in this chapter but only some more special
features. Many functions are almost the same as expalined in other examples.
The line numbers in the code snippets in this chapter can be somewhat different from the
latest project.
Android doesn't allow a program to start the GPS automaticaly for security reasons, only the user
can enable it.
If the GPS is disabled, the program must ask the user to enable it, this is done with the following
code (in the btnGPS_Touch routine in the Main module) :
Where:
GPSMinTime = the minimium time before the next fix.
GPSMinDistance = the minimum distance before the next fix.
To have the quickest sampling of the GPS enter zeros for both parameters : GPS1.Start(0,0)
14 GPS 183 Basic4Android Beginner's Guide
The buttons of the program show a tooltip on top of the screen when they are touched.
The views used for this are not Buttons but Panels, because Button don't have the Touch event and
Panels have it.
- First we dim a BitmapDrawable object that will contain the bitmap to display in the button.
- Select ACTION_DOWN,
- Check if GPS is OFF (GPS_On = False) or ON (GPS_On = True)
- Load the corresponding bitmap and
- Set it to the buttons background.
- Select ACTION_UP
- Check if the touch coordinates are within the button area. If yes we execute the function.
- Change the GPS_On variable
- Check if GPS_On = False (GPS disabled) we
14 GPS 184 Basic4Android Beginner's Guide
In this part we check if the move coordinates are in the area of a button and change the button
images, red in in the area and blue outsides.
In this part we check in what button area the UP coordinates are and execute, or not, the
corresponding functions.
The two routines below calculate the latitude X and longitude Y coordinates, in km,
from coordinate 0, 0 (equator and Greenwich meridian) to the given lat and lng coordinates.
lat and lng are in degrees, we need to transform them to radians
with lng / 180 * cPI and lat / 180 * cPI.
for Y (lat) we multiply the angle (in radians) by the earth radius (6371 km)
for X (lng) we multiply the angle (in radians) by the earth radius (6371 km)
and multiply by CosD(lat).
The EarthRadius variable is defined in the Process_Globals routine in the GPSPaths module.
The EarthRadius value used, 6371 km, is a mean value. In reality, the EarthRadius varies with the
latitude but for our calculations the assumption of a mean radius is enough accurate.
It's 'simply' the Earthradius multiplied by the angle lat , but the angle is in degrees so we need
to tranform it into radians.
The calculation for the lng coordinate is similar to the lat calculation.
But, the radius of a circle of latitude depends on the latitude,
so we need to multiply the result by the cosine of lat CosD(lat).
We use CosD because the angle is in degrees.
14 GPS 190 Basic4Android Beginner's Guide
a map is displayed.
The position is drawn on the transparent panel pnlMap which is on top of the Activity and the
MapViewer WebView. The code below is in:
Where:
Location1.Longitude, Location1.Latitude
are the current location coordinates in degrees.
MapCenter.Longitude, MapCenter.Latitude
are the current map center coordinates in degrees
MapScaleLng, MapScaleLat are the scales, degrees/pixel, of the current map.
xc, yc are the coordinates of the current location in pixels.
(Location1.Longitude - MapCenter.Longitude)
Is the x distance, in degrees, from the map center to the current location.
(Location1.Longitude - MapCenter.Longitude) / MapScaleLng
Is the x distance, in pixels, from the the map center to the current location.
Here we check if the current location reaches one of the maps border, and if true, we set the map
center coordinates to the current location coordinates and redraw the map.
Where:
MapScaleLng = Longitude scale in degrees/pixel
MapZoomLevel = Current map zoom level
TileSize = Map tile size in pixels
MapScaleLat = Latitude scale in degrees/pixel
MapCenter.Latitude = Center lat coordinate of the current map in degrees.
But this tile size must be changed according to the device's density, because on different devices
with almost the same physical dimensions, but different densities, the size of the map is the same.
That means that the tile size is proportional to the device density.
14 GPS 192 Basic4Android Beginner's Guide
We
define local variables
draw a transparent rectangle to erase the previous position
update the drawing
set the variables for the drawing
define the new surrounding rectangle
draw a horizontal line
draw a vertical line
draw a circle
update the drawing
If there are code sections you would like to be developped here, please post the qustions and
suggestions in the GPSExample thread on the users forum.
15 Basic language 193 Basic4Android Beginner's Guide
15 Basic language
In computer programming, BASIC (an acronym which stands for Beginner's All-purpose Symbolic
Instruction Code) is a family of high-level programming languages designed to be easy to use.
The original Dartmouth BASIC was designed in 1964 by John George Kemeny and Thomas
Eugene Kurtz at Dartmouth College in New Hampshire, USA to provide computer access to non-
science students. At the time, nearly all use of computers required writing custom software, which
was something only scientists and mathematicians tended to do. The language and its variants
became widespread on microcomputers in the late 1970s and 1980s.
BASIC remains popular to this day in a handful of highly modified dialects and new languages
influenced by BASIC such as Microsoft Visual Basic. (source Wikipedia).
This is a summary of the more detailed explanations in Process and Activity life cycle.
The program goes through following routines when starting from top to down:
One of the most current reason why an activity is paused, is an orientation change.
In that case the current activity is 'paused', and re-activated with the new orientation and goes at
least through the Activity_Resume routine, but normally through Globals, Activity_Create and
Activity_Resume.
The variable UserClosed can be used to differentiate if the Activity has been paused by the
Operating System (ex: orientation change) or by the user (ex: back button click).
15 Basic language 195 Basic4Android Beginner's Guide
5. Activity_Resume is called.
No code.
15.2 Expressions
Precedence level: In an expression, operations with level 1 are evaluated before operations with
level 2, which are evaluated before operations with level 3.
Examples:
4 + 5 * 3 + 2 = 21 > 4 + 15 + 2
(4 + 5) * (3 + 2) = 45 > 9*5
- 22 = - 4
(-2)2 = 4
15 Basic language 197 Basic4Android Beginner's Guide
In computer science in relational expressions an operator tests some kind of relation between two
entities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 >= 3).
In B4A these operators return True or False, depending on whether the conditional relationship
between the two operands holds or not (source Wikipedia).
In computer science, a Boolean expression is an expression that produces a Boolean value when
evaluated, i.e. one of True or False. A Boolean expression may be composed of a combination of
the Boolean constants True or False, Boolean-typed variables, Boolean-valued operators, and
Boolean-valued functions (source Wikipedia).
Boolean operators are used in conditional statements such as IF-Then and Select-Case.
Operator Comment
Or Boolean Or Z = X Or Y Z = True if X or Y is equal to True or both are True
And Boolean And Z = X And Y Z = True if X and Y are both equal to True
Not ( ) Boolean Not X = True Y = Not(X) > Y = False
Or And
X Y Z Z
False False False False
True False True False
False True True False
True True True True
The If-Then-Else structure allows to operate conditional tests and execute different code sections
according to the test result.
General case:
The tests can be any kind of conditional test with two possibilities True or False.
Some examples:
General case:
Examples:
The For–Next loop allows to repeat a certain number of times the same code.
Example:
i incremental variable
n1 initial value
n2 final value
n3 step
If the step value is equal to '+1' the step keyword is not needed.
is the same as
15.4.2 Do - Loop
Examples:
15.5 Subs
A Subroutine (“Sub”) is a piece of code. It can be any length, and it has a distinctive name
and a defined scope (in the means of variables scope discussed earlier). A Subroutine is
called “Sub” in Basci4Android code, and is equivalent to procedures, functions, methods and
subs in other programming languages. The lines of code inside a Sub are executed from
first to last, as described in the program flow chapter.
It is not recommended to have too long Subs, they get less readable.
15.5.1 Declaring
It starts with the keyword Sub, followed by the Sub’s name, followed by a parameter list, followed
by the return type and ends with the keywords End Sub.
Subs are always declared at the top level of the module – that is, you cannot nest two Subs
one inside the other.
When you want the lines of code in a Sub to execute, you simply write the Sub’s name.
For example:
15.5.3 Naming
Basically, you can name a Sub any name that’s legal for a variable. It is recommended to
name the Sub with a significant name, like CalcInterest in the example, so you can tell what it
does from reading the code.
There is no limit on the number of Subs you can add to your program, but it is not
allowed to have two Subs with the same name in the same module.
15 Basic language 204 Basic4Android Beginner's Guide
15.5.4 Parameters
Parameters can be transmitted to the Sub, this list follows the sub name between brackets.
The parameter types can be declared directly in the list.
15.6 Events
In Object-oriented programming we have objects which can react on different user actions called
events.
The number and type of events an object can raise depends on the type of the object.
User interface objects are called 'Views' in Android.
Events
CheckedChange
ItemLongClick
ValueChanged
FocusChanged
TextChanged
PageFinished
EnterPressed
TabChanged
LongClick
ItemClick
KeyPress
Touch
Down
Click
Up
Views
Activity
Button
CheckBox
EditText
ImageView
Label
ListView
Panel
RadioButton
SeekBar
Spinner
TabHost
ToggleButton
WebView
15 Basic language 206 Basic4Android Beginner's Guide
LongClick Event raised when the user clicks on the view and holds down a short
moment.
Example:
Example:
Example:
15 Basic language 207 Basic4Android Beginner's Guide
Example:
15 Basic language 208 Basic4Android Beginner's Guide
15.7 Libraries
The standard B4A libraries are saved in the Libraries folder in the B4A program folder.
Normally in: C:\Program Files\Anywhere Software\Basic4android\Libraries
For the additional libraries it is useful to setup a special folder to save them somewhere else.
For example: D:\Basic4Android\AddLibraries
When you install a new version of B4A, all standard libraries are automatically updated, but the
additional libraries are not included. The advantage of the special folder is that you don't need to
care about them because this folder is not affected when you install the new version of B4A.
The additional libraries are not systematically updated with new version of B4A.
When the IDE starts, it looks first for the available libraries in the Libraries folder of B4A and then
in the folder for the additional libraries.
15 Basic language 209 Basic4Android Beginner's Guide
If you setup a special additional libraries folder you must specify it in the IDE.
If you get this message, means that you forgot to check the specified library in the Lib Tab list !
15 Basic language 210 Basic4Android Beginner's Guide
Basic4Android allows string manipulations like other basic languages but with some differences.
Result: 123;234;45;23
Number formating, display numbers as strings with different formats, there are two keywords:
NumberFormat(Number As Double, MinimumIntegers As Int, MaximumFractions As Int)
NumberFormat(12345.6789, 0, 2) = 12,345.68
NumberFormat(1, 3 ,0) = 001
NumberFormat(Value, 3 ,0) variables can be used.
NumberFormat(Value + 10, 3 ,0) arithmetic operations can be used.
NumberFormat((lblscore.Text + 10), 0, 0) if one variable is a string add parentthesises.
15.9 Timers
A Timer object generates ticks events at specified intervals. Using a timer is a good alternative to a
long loop, as it allows the UI thread to handle other events and messages.
Note that the timer events will not fire while the UI thread is busy running other code (unless you
call DoEvents keyword).
Timer events will not fire when the activity is paused, or if a blocking dialog (like Msgbox) is
visible.
It is also important to disable the timer when the activity is pausing and then enable it when it
resumes. This will save CPU and battery.
A timer has:
Three parameters.
o Initialize Initializes the timer with two parameters, the EventName and the
interval.
Timer1.Initialize(EventName As String, Interval As Long)
Ex: Timer1.Initialize("Timer1", 1000)
One Event
o Tick The Tick routine is called every time interval.
Ex: Sub Timer1_Tick
But it must be initialized in the Activity_Create routine in the module where the timer tick
event routine is used.
15.10 Files
Many applications require access to a persistent storage. The two most common storage types are
files and databases.
The predefined object File has a number of functions for working with files.
Files locations - There are several important locations where you can read or write files.
File.DirAssets
The assets folder includes the files that were added with the file manager in the IDE.
These files are read-only.
You can not create new files in this folder (which is actually located inside the apk file).
If you have a database file in the Dir.Assets folder you need to copy it to another folder before you
can use it.
File.DirInternal / File.DirInternalCache
These two folders are stored in the main memory and are private to your application. Other
applications cannot access these files.
The cache folder may get deleted by the OS if it needs more space.
File.DirRootExternal
The storage card root folder.
File.DirDefaultExternal
The default folder for your application in the SD card.
The folder is: <storage card>/Android/data/<package>/files/
It will be created if required.
Note that calling any of the two above properties will add the EXTERNAL_STORAGE permission
to your application.
Tip: You can check if there is a storage card and whether it is available with
File.ExternalReadable and File.ExternalWritable.
The File object includes several methods for writing to files and reading from files.
To be able to write to a file or to read from a file, this one must be opened.
15 Basic language 213 Basic4Android Beginner's Guide
15.10.2 TextWriter
There are two other useful functions for text files: TextWriter and TextReader:
Example:
Dim Writer As TextWriter
Writer.Initialize(File.OpenOutput(File.DirRootExternal, "Test.txt" , False))
Example:
Dim Writer As TextWriter
Writer.Initialize2(File.OpenOutput(File.DirRootExternal,"Test.txt" ,False)," ISO-8859-1")
TextWriter.Close
- Closes the stream.
Example:
15 Basic language 215 Basic4Android Beginner's Guide
15.10.3 TextReader
There are two other useful functions for text files: TextWriter and TextReader:
Example:
Dim Reader TextReader
Reader.Initialize(File.InputOutput(File.DirRootExternal, "Test.txt"))
Example:
Dim Reader TextReader
Reader.Initialize(File.OpenInput(File.DirRootExternal, "Test.txt")," ISO-8859-1")
TextReader.ReadAll As String
- Reads all of the remaining text and closes the stream.
Example:
txt = Reader.ReadAll
TextReader.ReadLine As String
- Reads the next line from the stream.
The new line characters are not returned.
Returns Null if there are no more characters to read.
Example:
TextReader.ReadList As List
- Reads the remaining text and returns a List object filled with the lines.
Closes the stream when done.
Example:
List1 = Reader.ReadList
15 Basic language 216 Basic4Android Beginner's Guide
Text encoding or character encoding consists of a code that pairs each character from a given
repertoire with something else. Other terms like character set (charset), and sometimes character
map or code page are used almost interchangeably (source Wikipedia).
In Windows the most common character sets are ANSII and ANSIS.
ASCII includes definitions for 128 characters, 33 are non-printing control characters (now
mostly obsolete) that affect how text and space is processed.
ANSI, Windows-1252 or CP-1252 is a character encoding of the Latin alphabet, used by
default in the legacy components of Microsoft Windows in English and some other Western
languages with 256 definitions (one byte). The first 128 characters are the same as in the
ASCII encoding.
Many files generated by Windows programs are encoded with the ANSI characterset in western
countries.
For example: Excel csv files, Notepad files by default, but files can be saved, with Notepad, with
UTF-8 encoding.
To read Windows file encoded with ANSI you should use the ISO-8859-1 character set.
If you need to write files for use with Windows you should also use the ISO-8859-1 character set.
Another difference between Windows and Android is the end of line character:
Android, only the LF (Line Feed) character Chr(10) is added at the end of a line.
Windows, two characters CR (Carriage Return Chr(13)) and LF Chr(10) are added at the
end of a line. If you need to write files for Windows you must add CR yourself.
To read or write files with a different encoding you must use the TextReader or TextWriter objects
with the Initialize2 methods. Even for reading csv files.
15 Basic language 217 Basic4Android Beginner's Guide
Or
Read the whole file with TextReader.Initialize2 and "ISO-8859-1" encoding.
Save it back with TextWriter.Initialize with the standard Android encoding.
Read the file with LoadCSV or LoadCSV2 from the StringUtils library.
16 Graphics / Drawing 218 Basic4Android Beginner's Guide
16 Graphics / Drawing
16.1 Overview
3 buttons
o
starts rotating
o
step by step moving
o
we can let turn either the needle
or the compass.
2 bitmap files
o compass.png
o needle.png
In the DrawBitmapRotated function the bitmap rotates around the bitmaps centre.
If we had a needle image like this one, we would need to do some calculations to make sure that
it turns around the needle centre.
To avoid these calculations, the needle bitmap looks like this one. We added the lower part so
that the needle centre is at the bitmap's centre.
We change the Mode variable from True to False or from False to True with the Not
keyword.
If Mode = True, rotating needle, we:
o Set the button text to "Needle turns".
o Draw a transparent rectangle to erase the current needle.
o Draw the needle at the new position.
o Draw the default compass.
If Mode = False, rotating compass, we:
o Set the button text to "Compass turns".
o Erase the current needle
o Draw the new needle.
16 Graphics / Drawing 225 Basic4Android Beginner's Guide
In the second drawing program, SimpleDrawFunctions, we use the other common drawing
functions.
The program has no other utility than show what can be done with drawings.
The program has three Panels which we use as layers and three ToggleButtons buttons allowing us
to show or hide each layer.
Layer(0) has a grey background and the two other layers have a transparent background.
You can play with the buttons to show the different combinations of visible and hidden layers.
16 Graphics / Drawing 226 Basic4Android Beginner's Guide
You can play with the buttons to show the different combinations of visible and hidden layers.
16 Graphics / Drawing 228 Basic4Android Beginner's Guide
In the Sub Globals routine we declare the different views and variables:
We have:
3 Panels
3 Canvases
3 ToggleButtons
1 Rect, rectangle used to draw rectangles
1 Bitmap, holding the activity's background image
1 BitmapDrawable, holds the activity's background
different variables used for the drawing.
Note that we use arrays of views for the three panels, canvases and togglebuttons.
Dim pnlLayer(3) As Panel instead of Dim pnlLayer0, pnlLayer1, pnlLayer2 As Panel.
In the Sub Activity_Create routine we initialize the different views and add them to the activity:
We:
initialize the views only if FirstTime = True.
load the Rose2.jpg image file into the bitmap.
initialize the background image of the activity.
set the activity's background image
In a loop we:
initialize the layer Panels.
we define an individual EventName for each of the three Panels
we use only an event on layout(0).
add the panels to the activity.
initialize the layer Canvases.
set the Panels Tag parameter to the index.
draw the text "Rose" with the three different possible alignments.
draw the reference point for each text.
Looking closer on the displayed texts we see the reference point for each text.
LEFT alignment.
CENTER alignment.
RIGHT alignment.
dim a local Button to get the view that raised the event.
set Send to the Sender view
change the Visible parameter from True to False or from False to True.
draw a dark gray circle to erase the previous blue and transparent circle.
set xc and yc to the new coordinates of the circle centres.
draw a blue and transparent circle on layer(1).
invalidate pnlLayout(1) to force the update of the drawing.
17 Widgets 234 Basic4Android Beginner's Guide
Basic4android v1.6 adds support for home screen widgets. This tutorial will explain how to
implement your own home screen widgets (also named App Widgets).
It is important to understand that the widgets are created and managed in another process, different
than the process that your application is running in. The home screen application is hosting your
widgets.
This means that it is not possible to directly access the widgets views. Instead we are using a special
object named RemoteViews which gives us indirect access to the widget views.
Widgets do not support all views types. The following views are supported:
Button (default drawable)
Label (ColorDrawable or GradientDrawable)
Panel (ColorDrawable or GradientDrawable)
ImageView
ProgressBar (both modes)
The widget layout and configuration must be defined with XML files. During compilation
Basic4android reads the layout file created with the designer and generates the required XML files.
Each widget is tied to a Service module. Through this module the widget is created and updated.
Add a Service module. Note that the service module handling the widget is a standard
service.
Design the widget layout with the designer. First add a Panel and then add the other views to
this Panel.
The widget layout will be made from this panel.
Add code similar to the following code the service module:
17 Widgets 235 Basic4Android Beginner's Guide
Compile and run your application. Go to the home screen, long press on the screen and you
will see your widget listed on the widgets list.
As these arguments are read by the compiler, only strings or numbers are accepted.
Events:
The above code checks the Intent message that caused this service to start and is responsible for
raising the events related to the widget. It returns true if an event was raised.
The widget raises two events. RequestUpdate is raised when the widget needs to update itself. It
will fire after adding the widget to the screen, after the device has booted, based on the scheduled
updating interval (if set) or after the application was updated.
The Disabled event is raised when the last instance of our widget is removed from the screen.
17 Widgets 236 Basic4Android Beginner's Guide
As mentioned above all views support the Click event. All that needs to be done in order to handle
the click event of a button named Button1 is to add a sub named Button1_Click (the sub name
should actually match the EventName property which is by default the same as the name).
For example if you want to show the main Activity when the user presses on Button1 you can use
this code:
After writing all the changes we call rv.UpdateWidget to send the updates to the widget.
The example adds a simple widget. The widget doesn't do anything useful.
17 Widgets 237 Basic4Android Beginner's Guide
We will start with the layout. The widget is made of a Label for the text and an ImageView for the
arrow button.
You can see in the above picture that we use two panels. The base panel named pnlBase is a
transparent panel (Alpha=0). The base panel contains another panel which is the grey panel.
The purpose of the transparent panel is to add some padding to the other views. The widget size is
determined by the base panel. Without the transparent panel there will be no margin between the
visible widget and the screen left edge.
17 Widgets 238 Basic4Android Beginner's Guide
We are setting the base panel size to 294x72. This is the recommended size for a 4x1 cells widget.
Tip: in some cases when you change the layout and there is already an existing widget in the device,
the widget doesn't get updated. Remove the widget and add it again to see the change.
The widget is configured to be updated automatically every 24 hours. This is done in this line:
After 24 hours or when the widget is first added or after a boot the RequestUpdate event is raised.
First we clear the current quotes and then we fetch the new ones. Note that if the device was
sleeping at this time then the calls are likely to fail as most devices turn off the wifi while sleeping.
In this case new quotes will arrive when the user presses on the arrow button.
In cases like this you should not count on the automatic update to succeed and make sure that there
is an alternative way to update the widget.
Persisting the data. The process running our widget code will not stay alive forever. It will be
killed by the OS at some point.
Therefore we cannot rely on global variables to store our data.
All of the "state" variables must be written to a file.
RandomAccessFile.WriteObject and ReadObject are very useful for such tasks.
Each time that the widget sends a request to our application, Service_Start is called.
Not much is done in this sub:
17 Widgets 239 Basic4Android Beginner's Guide
However if our process is not alive yet then Service_Create will be called before. Service_Create is
an important point, as it allows us to read the previously saved state to memory:
18 B4A Keywords
List of types:
Bit
DateTime
Exception
Keywords
LayoutValues
String
StringBuilder
Timer
18.1 Bit
Bit is a predefined object containing bitwise related methods.
Example:
Dim flags As Int
flags = Bit.Or(100, 200)
Events:
None
Members:
Members description:
18.2 DateTime
Date and time related methods.
DateTime is a predefined object. You should not declare it yourself.
Date and time values are stored as ticks. Ticks are the number of milliseconds since January 1,
1970.
This value is too large to be stored in an Int variable. It should only be stored in a Long
variable.
The methods DateTime.Date and DateTime.Time convert the ticks value to a string.
You can get the current time with DateTime.Now.
18 B4A Keywords 242 Basic4Android Beginner's Guide
Example:
Dim now As Long
now = DateTime.Now
Msgbox("The date is: " & DateTime.Date(now) & CRLF & _
"The time is: " & DateTime.Time(now), "")
Events:
None
Members:
Add (Ticks As Long, Years As Int, Months As Int, Days As Int) As Long
DateFormat As String
TicksPerDay As Long
TicksPerHour As Long
TicksPerMinute As Long
TicksPerSecond As Long
TimeFormat As String
Members description:
18 B4A Keywords 243 Basic4Android Beginner's Guide
Add (Ticks As Long, Years As Int, Months As Int, Days As Int) As Long
Returns a ticks value which is the result of adding the specified time spans to the given ticks value.
Pass negative values if you want to subtract the values.
Example:
Dim Tomorrow As Long
Tomorrow = DateTime.Add(DateTime.Now, 0, 0, 1)
Log("Tomorrow date is: " & DateTime.Date(Tomorrow))
DateFormat As String
Gets or sets the format used to parse date strings.
See this page for the supported patterns: formats.
The default pattern is MM/dd/yyyy (04/23/2002 for example).
TicksPerDay As Long
TicksPerHour As Long
TicksPerMinute As Long
TicksPerSecond As Long
TimeFormat As String
Gets or sets the format used to parse time strings.
See this page for the supported patterns: formats.
The default pattern is HH:mm:ss (23:45:12 for example).
18.3 Exception
Holds a thrown exception.
You can access the last thrown exception by calling LastException.
For example:
Try
Dim in As InputStream
in = File.OpenInput(File.DirInternal, "SomeMissingFile.txt")
'...
Catch
Log(LastException.Message)
End Try
If in.IsInitialized Then in.Close
18 B4A Keywords 245 Basic4Android Beginner's Guide
Events:
None
Members:
IsInitialized As Boolean
Members description:
IsInitialized As Boolean
18.4 Keywords
These are the internal keywords.
Events:
None
Members:
Array
BytesToString (Data() As Byte, StartOffset As Int, Length As Int, CharSet As String) As String
Catch
cE As Double
Continue
cPI As Double
CRLF As String
Density As Float
Dim
DoEvents
Exit
ExitApplication
False As Boolean
File As File
For
GetDeviceLayoutValues As LayoutValues
If
Is
LastException As Exception
Int) As Bitmap
Msgbox2 (Message As String, Title As String, Positive As String, Cancel As String, Negative
As String, Icon As android.graphics.Bitmap) As Int
Null As Object
ProgressDialogHide
QUOTE As String
Regex As Regex
Return
Select
Sender As Object
18 B4A Keywords 248 Basic4Android Beginner's Guide
Sub
TAB As String
True As Boolean
Try
Type
Until
While
Members description:
Array
Creates a single dimension array of the specified type.
The syntax is: Array As type (list of values).
Example:
Dim Days() As String
Days = Array As String("Sunday", "Monday", ...)
Catch
Any exception thrown inside a try block will be caught in the catch block.
Call LastException to get the caught exception.
Syntax:
Try
...
Catch
...
End Try
cE As Double
e (natural logarithm base) constant.
Continue
Stops executing the current iteration and continues with the next one.
cPI As Double
PI constant.
CRLF As String
New line character. The value of Chr(13).
Density As Float
Returns the device scale, which is DPI / 160.
(DPI stands for dots per inch).
Dim
Declares a variable.
Syntax:
Declare a single variable:
Dim variable name [As type]
The default type is String.
Declare an array:
Dim variable(Rank1, Rank2, ...) [As type]
Example:Dim Days(7) As String
The actual rank can be omitted for zero length arrays.
Note that a shorthand syntax for this method is available. Any number followed by the string 'dip'
will be converted in the same manner (no spaces are allowed between the number and 'dip').
So the previous code is equivalent to:
Button1.Width = 100dip 'dip -> density independent pixel
DoEvents
Processes waiting messages in the messages queue.
DoEvents can be called inside lengthy loops to allow the program to process waiting events.
Exit
Exits the most inner loop.
18 B4A Keywords 251 Basic4Android Beginner's Guide
ExitApplication
Immediately ends the application and stops the process.
Most applications should not use this method and prefer Activity.Finish which lets the OS decide
when the process is killed.
False As Boolean
File As File
Files related methods.
For
Syntax:
For variable = value1 To value2 [Step interval]
...
Next
Example:
For i = 1 To 10
Log(i) 'Will print 1 to 10 (inclusive).
Next
If the iterator variable was not declared before it will be of type Int.
GetDeviceLayoutValues As LayoutValues
Returns the device LayoutValues.
Example:
Log(GetDeviceLayoutValues)
If
Single line:
If condition Then true-statement [Else false-statement]
Multiline:
If condition Then
statement
Else If condition Then
statement
...
Else
statement
End If
Returns the index of the selected item or DialogResponse.Cancel if the user pressed on the back
key.
List - Items to display.
Title - Dialog title.
CheckedItem - The index of the item that will first be selected. Pass -1 if no item should be
preselected.
Is
Tests whether the object if of the given type.
Example:
For i = 0 To Activity.NumberOfViews - 1
If Activity.GetView(i) Is Button Then
Dim b As Button
b = Activity.GetView(i)
b.Color = Colors.Blue
End If
Next
LastException As Exception
Returns the last exception that was caught (if such exists).
Activity.SetBackgroundImage(LoadBitmapSample(File.DirAssets,
"SomeFile.jpg", Activity.Width, Activity.Height))
Null As Object
A shorthand syntax for this method is available. Any number followed by the string '%x'
will be converted in the same manner (no spaces are allowed between the number and '%x').
So the previous code is equivalent to:
Button1.Width = 50%x
A shorthand syntax for this method is available. Any number followed by the string '%y'
will be converted in the same manner (no spaces are allowed between the number and '%y').
So the previous code is equivalent to:
Button1.Height = 50%y
ProgressDialogHide
Hides a visible progress dialog. Does not do anything if no progress dialog is visible.
QUOTE As String
Quote character. The value of Chr(34).
18 B4A Keywords 255 Basic4Android Beginner's Guide
Regex As Regex
Regular expressions related methods.
Return
Returns from the current sub and optionally returns the given value.
Syntax: Return [value]
Select
Compares a single value to multiple values.
Select blocks cannot be nested.
Example:
Dim value As Int
value = 7
Select value
Case 1:
Log("One")
Case 2, 4, 6, 8:
Log("Even")
Case 3, 5, 7, 9:
Log("Odd larger than one")
Case Else
Log("Larger than 9")
End Select
Sender As Object
Returns the object that raised the event.
Only valid while inside the event sub.
Example:
Sub Button_Click
Dim b As Button
b = Sender
b.Text = "I've been clicked"
End Sub
Sub
Declares a sub with the parameters and return type.
Syntax: Sub name [(list of parameters)] [As return-type]
Parameters include name and type.
The lengths of arrays dimensions should not be included.
Example:
Sub MySub (FirstName As String, LastName As String, Age As Int,
OtherValues() As Double) As Boolean
...
End Sub
In this example OtherValues is a single dimension array.
The return type declaration is different than other declarations as the array parenthesis follow the
type and not
the name (which does not exist in this case).
TAB As String
Tab character.
True As Boolean
Try
Any exception thrown inside a try block will be caught in the catch block.
Call LastException to get the caught exception.
Syntax:
Try
...
Catch
18 B4A Keywords 257 Basic4Android Beginner's Guide
...
End Try
Type
Declares a structure.
Can only be used inside sub Globals or sub Process_Globals.
Syntax:
Type type-name (field1, field2, ...)
Fields include name and type.
Example:
Type MyType (Name As String, Items(10) As Int)
Dim a, b As MyType
a.Initialize
a.Items(2) = 123
Until
Loops until the condition is true.
Syntax:
Do Until condition
...
Loop
While
Loops while the condition is true.
Syntax:
Do While condition
...
Loop
18.5 LayoutValues
Holds values related to the display.
You can get the values of the the current display by calling GetDeviceLayoutValues.
For example:
Dim lv As LayoutValues
lv = GetDeviceLayoutValues
Log(lv) 'will print the values to the log
Activity.LoadLayout and Panel.LoadLayout return a LayoutValues object with the
values of the
chosen layout variant.
Events:
None
Members:
Height As Int
Scale As Float
toString As String
18 B4A Keywords 258 Basic4Android Beginner's Guide
Width As Int
Members description:
Height As Int
The display height (pixels).
Scale As Float
The device scale value which is equal to 'dots per inch' / 160. For most devices the value will be 1.0
or 1.5 (high resolution).
toString As String
Width As Int
The display width (pixels).
18.6 String
Strings are immutable in Basic4android, which means that you can change the value of a string
variable but you cannot change the text stored in a string object.
So methods like SubString, Trim and ToLowerCase return a new string, they do not change the
value of the current string.
Typical usage:
Dim s As String
s = "some text"
s = s.Replace("a", "b")
You can use StringBuilder if you need a mutable string.
Note that string literals are also string objects:
Log(" some text ".Trim)
Events:
None
Members:
Length As Int
18 B4A Keywords 259 Basic4Android Beginner's Guide
ToLowerCase As String
ToUpperCase As String
Trim As String
Members description:
Examples:
"abc".CompareTo("da") ' < 0
"abc".CompareTo("Abc") ' > 0
"abc".CompareTo("abca")' < 0
Returns the index of the first occurrence of SearchFor string in the string.
Starts searching from the given Index.
Returns -1 if SearchFor was not found.
Length As Int
Returns the length of this string.
Example:
"012345".SubString(2) 'returns "2345"
Example:
"012345".SubString2(2, 4) 'returns "23"
ToLowerCase As String
Returns a new string which is the result of lower casing this string.
ToUpperCase As String
Returns a new string which is the result of upper casing this string.
Trim As String
Returns a copy of the original string without any leading or trailing white spaces.
18.7 StringBuilder
StringBuilder is a mutable string, unlike regular strings which are immutable.
StringBuilder is especially useful when you need to concatenate many strings.
The following code demonstrates the performance boosting of StringBuilder:
Dim start As Long
start = DateTime.Now
'Regular string
Dim s As String
For i = 1 To 5000
s = s & i
18 B4A Keywords 261 Basic4Android Beginner's Guide
Next
Log(DateTime.Now - start)
'StringBuilder
start = DateTime.Now
Dim sb As StringBuilder
sb.Initialize
For i = 1 To 5000
sb.Append(i)
Next
Log(DateTime.Now - start)
Tested on a real device, the first 'for loop' took about 20 seconds and the second took less then tenth
of a second.
The reason is that the code: s = s & i creates a new string each iteration (strings are
immutable).
The method StringBuilder.ToString converts the object to a string.
Events:
None
Members:
Initialize
IsInitialized As Boolean
ToString As String
Members description:
Initialize
Initializes the object.
Example:
Dim sb As StringBuilder
sb.Initialize
sb.Append("The value is: ").Append(SomeOtherVariable).Append(CRLF)
IsInitialized As Boolean
ToString As String
Converts the object to a string.
18.8 Timer
A Timer object generates ticks events at specified intervals.
Using a timer is a good alternative to a long loop, as it allows the UI thread to handle other events
and messages.
Note that the timer events will not fire while the UI thread is busy running other code (unless you
call DoEvents keyword).
The timer Enabled property is set to False by default. To make it start working you should change it
to True.
Timer events will not fire when the activity is paused, or if a blocking dialog (like Msgbox) is
visible.
Timers should be declared in Sub Process_Globals. Otherwise you may get multiple timers
running when the activity is recreated.
It is also important to disable the timer when the activity is pausing and then enable it when it
resumes. This will save CPU and battery.
Events:
Tick
Members:
Enabled As Boolean
Interval As Long
Members description:
Enabled As Boolean
Gets or sets whether the timer is enabled (ticking).
Example:
Timer1.Initialize("Timer1", 1000)
Timer1.Enabled = True
Sub Timer1_Tick
'Handle tick events
End Sub
Interval As Long
Gets or sets the interval between tick events, measured in milliseconds.
19 Views 264 Basic4Android Beginner's Guide
19 Views
List of types:
Activity
Button
CheckBox
EditText
ImageView
Label
ListView
Panel
ProgressBar
RadioButton
ScrollView
SeekBar
Spinner
TabHost
ToggleButton
View
WebView
19.1 Activity
Each activity module include a predefined Activity object.
Activity is the main component of your application.
Activities have three special life cycle related event: Activity_Create, Activity_Resume and
Activity_Pause.
See this tutorial for more information about activities and processes life cycle: Life cycle tutorial.
You can add and remove views to this activity with AddView and RemoveViewAt methods.
You can also load a layout file with LoadLayout.
The Touch event can be used to handle user touches.
The first parameter of this event is the Action parameter. The parameter values can be
ACTION_DOWN,
ACTION_MOVE or ACTION_UP. Use this value to find the user current action.
The KeyPress event occurs when the user has pressed on the key and assuming that no other view
has consumed this event (like EditText).
When handling the KeyPress event you should return a boolean value which tells whether the key
press event was consumed.
For example if the user pressed on the Back key and you return True then the OS will not close your
activity.
Events:
Touch (Action As Int, X As Float, Y As Float)
KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
Click
LongClick
Members:
ACTION_DOWN As Int
ACTION_MOVE As Int
ACTION_UP As Int
AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As Int)
Background As android.graphics.drawable.Drawable
BringToFront
Finish
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
19 Views 266 Basic4Android Beginner's Guide
RequestFocus As Boolean
SendToBack
Tag As Object
Title As CharSequence
Top As Int
Width As Int
Members description:
ACTION_DOWN As Int
ACTION_MOVE As Int
ACTION_UP As Int
...
Sub OpenFile_Click
...
End Sub
AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As
Int)
Adds a view to this activity.
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Finish
Closes this activity.
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
19 Views 268 Basic4Android Beginner's Guide
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Title As CharSequence
Top As Int
Width As Int
Gets or sets the view's width.
19.2 Button
A Button view.
If you change the button's background you will usually want to use StateListDrawable which allows
you to set the "default" drawable
and the "pressed" drawable.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
19 Views 269 Basic4Android Beginner's Guide
Down
Up
Click
LongClick
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
19 Views 270 Basic4Android Beginner's Guide
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
19 Views 271 Basic4Android Beginner's Guide
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.3 CheckBox
Events:
CheckedChange(Checked As Boolean)
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
19 Views 273 Basic4Android Beginner's Guide
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
19 Views 274 Basic4Android Beginner's Guide
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.4 EditText
EditText view is a view that allows the user to write free text (similar to WinForms TextBox).
The EditText has two modes; SingleLine and MultiLine. You can set it to be multiline by calling
EditText1.SingleLine = False
On most devices the soft keyboard will show automatically when the user presses on the EditText.
You can change the InputType property and change the type of keyboard that appears.
For example: EditText1.InputType = EditText1.INPUT_TYPE_NUMBERS will cause
the numeric keyboard to appear when
the user presses on the EditText. Note that it will also cause the EditText to only accept numbers.
The TextChanged event fires whenever the text changes and it includes the old and new strings.
The EnterPressed event fires when the user presses on the enter key or action key (Done or Next).
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
TextChanged (Old As String, New As String)
EnterPressed
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Gravity As Int
Height As Int
Hint As String
HintColor As Int
INPUT_TYPE_DECIMAL_NUMBERS As Int
INPUT_TYPE_NONE As Int
INPUT_TYPE_NUMBERS As Int
INPUT_TYPE_PHONE As Int
INPUT_TYPE_TEXT As Int
InputType As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SelectAll
SelectionStart As Int
SendToBack
Tag As Object
19 Views 276 Basic4Android Beginner's Guide
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Gravity As Int
Height As Int
Hint As String
Gets or sets the text that will appear when the EditText is empty.
Example:
EditText1.Hint = "Enter username"
HintColor As Int
19 Views 277 Basic4Android Beginner's Guide
INPUT_TYPE_DECIMAL_NUMBERS As Int
Numeric keyboard will be displayed. Numbers, decimal point and minus sign are accepted.
INPUT_TYPE_NONE As Int
No keyboard will be displayed.
INPUT_TYPE_NUMBERS As Int
Numeric keyboard will be displayed. Only numbers are accepted.
INPUT_TYPE_PHONE As Int
Keyboard will be displayed in phone mode.
INPUT_TYPE_TEXT As Int
Default text mode.
InputType As Int
Gets or sets the input type flag. This flag is used to determine the settings of the virtual keyboard.
Example:
EditText1.InputType = EditText1.INPUT_TYPE_NUMBERS
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SelectAll
Selects the entire text.
SelectionStart As Int
Gets or sets the selection start position (or the cursor position).
Returns -1 if there is no selection or cursor.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.5 ImageView
Events:
Click
LongClick
Members:
Background As android.graphics.drawable.Drawable
Bitmap As android.graphics.Bitmap
BringToFront
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
19 Views 280 Basic4Android Beginner's Guide
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
Bitmap As android.graphics.Bitmap
Gets or sets the bitmap assigned to the ImageView.
Example:
ImageView1.Bitmap = LoadBitmap(File.DirAssets, "someimage.jpg")
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Gravity As Int
Gets or sets the gravity assigned to the bitmap.
Example:
ImageView1.Gravity = Gravity.Fill
Height As Int
Invalidate
19 Views 281 Basic4Android Beginner's Guide
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19 Views 282 Basic4Android Beginner's Guide
19.6 Label
Events:
Click
LongClick
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Text As String
19 Views 283 Basic4Android Beginner's Guide
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
19 Views 284 Basic4Android Beginner's Guide
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19 Views 285 Basic4Android Beginner's Guide
19.7 ListView
ListView is a very useful view that can handle large and small lists.
The ListView raises two events. ItemClick is raised when an item is clicked and ItemLongClick is
raised when an item is clicked and held.
See the ListView tutorial for more information.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
ItemClick (Position As Int, Value As Object)
ItemLongClick (Position As Int, Value As Object)
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Clear
Enabled As Boolean
FastScrollEnabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
19 Views 287 Basic4Android Beginner's Guide
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
19 Views 288 Basic4Android Beginner's Guide
Clear
Clears all items from the list.
Enabled As Boolean
FastScrollEnabled As Boolean
Gets or sets whether the fast scroll icon will appear when the user scrolls the list.
The default is false.
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
19 Views 289 Basic4Android Beginner's Guide
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.8 Panel
Events:
Touch (Action As Int, X As Float, Y As Float)
Click
LongClick
Members:
AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As Int)
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
AddView (View As android.view.View, Left As Int, Top As Int, Width As Int, Height As
Int)
Adds a view to this panel.
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
19 Views 293 Basic4Android Beginner's Guide
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.9 ProgressBar
A progress bar view. The Progress property sets the progress value which is between 0 to 100.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
None
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
Progress As Int
RemoveView
RequestFocus As Boolean
19 Views 294 Basic4Android Beginner's Guide
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
19 Views 295 Basic4Android Beginner's Guide
Left As Int
Progress As Int
Gets or sets the progress value.
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.10 RadioButton
A RadioButton view. Only one RadioButton in a group can be checked. When a different
RadioButton is checked all others will
automatically be unchecked. Grouping is done by adding RadioButtons to the same activity or
panel.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
CheckedChange(Checked As Boolean)
Members:
Background As android.graphics.drawable.Drawable
19 Views 296 Basic4Android Beginner's Guide
BringToFront
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Members description:
19 Views 297 Basic4Android Beginner's Guide
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
19 Views 298 Basic4Android Beginner's Guide
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Text As String
TextColor As Int
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.11 ScrollView
ScrollView is a view that contains other views and allows the user to vertically scroll those views.
See the ScrollView tutorial for more information.
The ScrollView has an inner panel which actually contains the child views.
You can add views by calling: ScrollView1.Panel.AddView(...)
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
19 Views 299 Basic4Android Beginner's Guide
None
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
ScrollPosition As Int
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
19 Views 300 Basic4Android Beginner's Guide
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
ScrollPosition As Int
Gets or sets the scroll position.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.12 SeekBar
A view that allows the user to set a value by dragging a slider. Similar to WinForms TrackBar.
The ValueChanged event is raised whenever the value is changed. The UserChanged parameter can
be used to distinguish between changes done by the user and changes done programmatically.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
ValueChanged (Value As Int, UserChanged As Boolean)
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
Max As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
Value As Int
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
Max As Int
Gets or sets the maximum allows value.
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Value As Int
19 Views 304 Basic4Android Beginner's Guide
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.13 Spinner
A folded list that opens when the user clicks on it and allows the user to choose an item. Similar to
WinForms ComboBox.
The ItemClick event is raised each time a user presses on an item (even if it is the already selected
item).
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
ItemClick (Position As Int, Value As Object)
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Clear
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
Prompt As String
RemoveView
RequestFocus As Boolean
SelectedIndex As Int
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
19 Views 306 Basic4Android Beginner's Guide
Clear
Clears all items.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
Prompt As String
Gets or sets the title that will be displayed when the spinner is opened.
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
19 Views 307 Basic4Android Beginner's Guide
SelectedIndex As Int
Gets or sets the index of the selected item. Returns -1 if no item is selected.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19 Views 308 Basic4Android Beginner's Guide
19.14 TabHost
TabHost is a view that contains multiple tab pages. Each tab page contains other child views.
See the TabHost tutorial for more information.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
TabChanged
Click
LongClick
Members:
Background As android.graphics.drawable.Drawable
BringToFront
CurrentTab As Int
Enabled As Boolean
Height As Int
19 Views 309 Basic4Android Beginner's Guide
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
Members description:
SelectedBitmap - The icon that will be drawn when the page is selected.
LayoutFile - A layout file describing the page layout.
Example:
Dim bmp1, bmp2 As Bitmap
bmp1 = LoadBitmap(File.DirAssets, "ic.png")
bmp2 = LoadBitmap(File.DirAssets, "ic_selected.png")
TabHost1.AddTabWithIcon("Page 1", bmp1, bmp2,"tabpage1.bal")
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
CurrentTab As Int
Gets or sets the current tab.
Example:
TabHost1.CurrentTab = (TabHost1.CurrentTab + 1) Mod
TabHost1.TabCount 'switch to the next tab.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19 Views 312 Basic4Android Beginner's Guide
19.15 ToggleButton
A ToggleButton view. This view which is similar to a button has two modes: ON and OFF.
When the user presses on it, it will change its mode.
You can set the text with the TextOn and TextOff properties.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
CheckedChange(Checked As Boolean)
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
TextColor As Int
TextOff As String
TextOn As String
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Checked As Boolean
Enabled As Boolean
Gravity As Int
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
TextColor As Int
TextOff As String
Gets or sets the text that will appear in the OFF mode.
TextOn As String
Gets or sets the text that will appear in the ON mode.
TextSize As Float
Top As Int
Typeface As android.graphics.Typeface
Visible As Boolean
Width As Int
Gets or sets the view's width.
19 Views 315 Basic4Android Beginner's Guide
19.16 View
View is a special type of object. You cannot create new View objects. However all other view types
can be assigned to a view variable.
This allows you to access the shared properties of all views.
For example this code hides all views of an activity:
For i = 0 To Activity.NumberOfViews - 1
Dim v As View
v = Activity.GetView(i)
v.Visible = False
Next
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Events:
Click
LongClick
Members:
Background As android.graphics.drawable.Drawable
BringToFront
Enabled As Boolean
Height As Int
Invalidate
IsInitialized As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
19 Views 316 Basic4Android Beginner's Guide
Top As Int
Visible As Boolean
Width As Int
Members description:
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
19 Views 317 Basic4Android Beginner's Guide
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
19.17 WebView
The WebView view uses the internal WebKit engine to display Html pages.
The page displayed can be an online page loaded with LoadUrl or a Html string loaded with
LoadHtml.
This is an 'Activity Object', it cannot be declared under Sub Process_Globals.
Permissions:
android.permission.INTERNET
Events:
None
Members:
Back
Background As android.graphics.drawable.Drawable
19 Views 318 Basic4Android Beginner's Guide
BringToFront
Enabled As Boolean
Forward
Height As Int
Invalidate
IsInitialized As Boolean
JavaScriptEnabled As Boolean
Left As Int
RemoveView
RequestFocus As Boolean
SendToBack
Tag As Object
Top As Int
Visible As Boolean
Width As Int
ZoomEnabled As Boolean
Members description:
19 Views 319 Basic4Android Beginner's Guide
Back
Goes back to the previous Url.
Background As android.graphics.drawable.Drawable
Gets or sets the background drawable.
BringToFront
Changes the Z order of this view and brings it to the front.
Enabled As Boolean
Forward
Goes forward to the next Url.
Height As Int
Invalidate
Invalidates the whole view forcing the view to redraw itself.
Redrawing will only happen when the program can process messages. Usually when it finishes
running the current code.
IsInitialized As Boolean
JavaScriptEnabled As Boolean
Gets or sets whether JavaScript is enabled.
JavaScript is enabled by default.
Left As Int
RemoveView
Removes this view from its parent.
RequestFocus As Boolean
Tries to set the focus to this view.
Returns True if the focus was set.
SendToBack
Changes the Z order of this view and sends it to the back.
Tag As Object
Gets or sets the Tag value. This is a place holder which can used to store additional data.
Top As Int
Visible As Boolean
Width As Int
Gets or sets the view's width.
ZoomEnabled As Boolean
Gets or sets whether the internal zoom feature is enabled.
The zoom feature is enabled by default.
20 VB6 versus B4A 321 Basic4Android Beginner's Guide
VB6 B4A
=== ===
controls Views (button, edittext, label, etc.)
In the VB6 code window, the top left drop-down list contains all
the controls you have placed in the current form and the right list
contains all the events for each control. The equivalent in B4A can
be found by clicking on Designer - Tools - Generate Members. Once
you have created Subs in the program coding window, the tab "Modules"
on the right side will list each of the Subs.
Dim/ReDim:
---------
Dim Array(n) Dim Array(n+1)
While "n" is the last index number in VB6, it indicates the number
of array elements when used in B4A. For example, to Dim an array
with 0-32 elements in VB6, you would say Dim A(32), while to convert
this to B4A, you need to change it to Dim A(33), yet index #33 is
never used (doing so would cause an out-of-range error).
Global Const x=1 B4A does not have a Global Const function.
In Sub Globals, you can say Dim x as Int: x = 1
but x is not a constant (it's value can be changed).
Colors:
------
20 VB6 versus B4A 322 Basic4Android Beginner's Guide
Calling a sub:
-------------
SubName x, y SubName(x, y)
General:
-------
DoEvents same, except that Erel says:
"Calling DoEvents in a loop consumes a lot of resources and
it doesn't allow the system to process all waiting messages
properly." This was in response to my pointing out that
while
in a Do Loop with DoEvents in it, WebView could not be
loaded
or if loaded, would not process a hyperlink click. And
Agraham
says: "Looping is bad practice on mobile devices. The CPU
will
be constantly executing code and using battery power as the
code will never get back to the OS idle loop where the
hardware
power saving measures are invoked."
control.SetFocus view.RequestFocus
TabIndex:
--------
In VB6, TabIndex can be set to control the order in which controls get focus
when Tab is pressed. According to Erel, in B4A:
"Android handles the sequence according to their position. You can set
EditText.ForceDone = True in all your EditTexts. Then catch the
EditText_EnterPressed event and explicitly set the focus to the next
view (with EditText.RequestFocus)."
Constants:
---------
"" Quote = Chr$(34)
vbCr CRLF = Chr$(13)
vbCrLf none
String "Members":
----------------
VB6 uses a character position pointer starting with 1.
B4A uses a character Index pointer starting with 0.
VB6 B4A
Mid$("abcde", 1, 1) = "a" = letter array index 0 -- "a" = "abcde".CharAt(0)
Mid$("abcde", 2, 1) = "b" = letter array index 1
Mid$("abcde", 3, 1) = "c" = letter array index 2
Mid$("abcde", 4, 1) = "d" = letter array index 3
Mid$("abcde", 5, 1) = "e" = letter array index 4
VB6 B4A
=== ===
Mid$(text, n, 1) text.CharAt(n-1)
Mid$(text, n) text.SubString(n-1)
Mid$(text, n, x) [x=length wanted] text.SubString2(n-1, n+x-1) [n+x-1=end
position]
Mid$(text, n, x) = text2 text = text.SubString2(0, n-2) & _
20 VB6 versus B4A 324 Basic4Android Beginner's Guide
Error Trapping:
--------------
VB6:
===
Sub SomeSub
On [Local] Error GoTo ErrorTrap
...some code...
On Error GoTo 0 [optional end to error trapping]
...optional additional code...
Exit Sub [to avoid executing ErrorTrap code]
ErrorTrap:
...optional code for error correction...
Resume [optional: "Resume Next" or "Resume [line label]".
End Sub
B4A:
===
Sub SomeSub
Try
...some code...
Catch [only executes if error above]
Log(LastException) [optional]
...optional code for error correction...
End Try
...optional additional code...
End Sub
WIth B4A, if you get an error caught in the middle of a large subroutine, you
can
NOT make a correction and resume within the code you were executing. Only the
code
in "Catch" gets executed. That would seem to make Try-Catch-End Try of use
mainly
during development.
Start the code with "Try" and replace the [line label] with "Catch".
Replace "GoTo [line label]" with code which will create an exception, which
causes
a jump to "Catch", such as OpenInput("bad path", "bad filename").
In the B4A environment, the Logs tab on the right side of the IDE is a
way to show the values of variables, etc., while the code is running.
Both VB6 and (now) B4A allow single-stepping through the code while it
is running and viewing the values of variables. VB6 also allows changing
the value of variables, changing the code, jumping to other lines from
the current line, etc. Because B4A runs on a PC while the app runs on
a separate device, B4A is currently unable to duplicate all of these
VB6 debug features.
21 FAQ 326 Basic4Android Beginner's Guide
21 FAQ
Some of the chapters below have been picked up from the forum.
When I try to compile or open the Designer I see a message saying: "Please save source code first."
A new project doesn't have a containing folder until it is first saved.
Save your project and this error will go away.
At the bottom of this page there is a long list with all the
objects types.
A list of the official and additional libraries with links to the relevant forum threads is shown in the
B4A Wiki here: Libraries
View.
Views added
in the Designer in a layout file MUST NOT be initialized !
o Just Dim the View in the Sub Globals routine.
o Initialize it and add it to the Activity (or a Panel) in the Activity_Create routine.
List / Map.
List and Map objects must be Initialized before they can be used.
21 FAQ 328 Basic4Android Beginner's Guide
To split a long line into two or more lines put an underscore character, seperated by a blank
character, at the end of the line. Look at the example in the chapter below.
Becomes:
Proposed by alfcen:
Suppose you have an Activity containing several buttons with Click events.
Now, you add a Panel onto the Activity, thus covering buttons. As you tap on the
panel you will see that a click event was fired on a button on the Activity.
This is NOT a B4A bug, on the contrary, it might be quite useful.
However, if this is not wanted, just add:
Activity.AddMenuItem("Title", "EventName")
Activity.AddMenuItem("Title", "EventName", Image)
Examples:
or
21 FAQ 330 Basic4Android Beginner's Guide
If you often get this message "Process has timeout" you can change its value:
In the IDE menu Tools / IDE Options click on Configure Process Timeout.
To delete files from the project you must use the files Tab in the lower right corner of the IDE.
Both
Portrait
Landscape
It can also be done by code with SetScreenOrientation from the Phone library:
Landscape
Phone1.SetScreenOrientation(0)
Portrait
Phone1.SetScreenOrientation(1)
Both
Phone1.SetScreenOrientation(-1)
21 FAQ 333 Basic4Android Beginner's Guide
You can take a screenshot of the device or the Emulator with following code:
Sub btnScrShot_LongClick
' Take a screenshot.
Dim Obj1, Obj2 As Reflector
Dim bmp As Bitmap
Dim c As Canvas
Dim now, i As Long
Dim dt As String
DateTime.DateFormat = "yyMMddHHmmss"
now = DateTime.Now
dt = DateTime.Date(now) ' e.g.: "110812150355" is Aug.12, 2011, 3:03:55 p.m.
Obj1.Target = Obj1.GetActivityBA
Obj1.Target = Obj1.GetField("vg")
bmp.InitializeMutable(Activity.Width, Activity.Height)
c.Initialize2(bmp)
Dim args(1) As Object
Dim types(1) As String
Obj2.Target = c
Obj2.Target = Obj2.GetField("canvas")
args(0) = Obj2.Target
types(0) = "android.graphics.Canvas"
Obj1.RunMethod4("draw", args, types)
Dim Out As OutputStream
Out = File.OpenOutput(File.DirRootExternal, dt & ".png", False)
bmp.WriteToStream(out, 100, "PNG")
Out.Close
End Sub
The compiler generates an *.apk file which is located in the 'Objects' folder. When the IDE is
connected to a device or to the Emulator the apk file is automaticaly uploaded to it.
The name of the apk file is the 'Application Label' you entered when you defined the project.
Example: GPSExample.apk
If you have checked 'Include Debug Information' and 'Attach Debugger' in the IDE you will get an
apk file with the _DEBUG suffix.
Example: GPSExample_DEBUG.apk
If you want to distribute your application you should uncheck these two options.
21 FAQ 334 Basic4Android Beginner's Guide
The code below shows how to run an application from another one.
The PackageManager is an object in the Phone library.
The exact package name is needed !
Code example.
You need to specify the rank (number of dimensions) in the Sub definition with ',' .
If you want the Sub return an array you must also speccify it.
You can get the currently language and country from a device with following code.
Needs the Reflection library (available only for users who baught Basic4Android) !
Examples:
22 Glossary
Android Android is a software stack for mobile devices that includes an operating system,
middleware and key applications. Google Inc. purchased, in 2005, Android Inc. the company that
initially developed the software.
Activity An activity is a single, focused thing that the user can do. Almost all activities
interact with the user, so the Activity class takes care of creating a window for you in which you
can place your UI.
View Provides classes that expose basic user interface classes that handle screen layout and
interaction with the user. Examples: Label, Panel, Button, EditText etc.