Unit 6-MAD
Unit 6-MAD
Unit 6-MAD
UNIT 6
Advanced Concepts
String Manipulations
These manipulations can be done directly on a string.
Example:
txt = "123,234,45,23"
txt = txt.Replace(",", ";")
Result: 123;234;45;23
The different functions are:
• CharAt(Index) Returns the character at the given index.
• CompareTo(Other) Lexicographically compares the string with the Other string.
• Contains(SearchFor) Tests whether the string contains the given SearchFor string.
• EndsWith(Suffix) Returns True if the string ends with the given Suffix substring.
• EqualsIgnoreCase(Other) Returns True if both strings are equal ignoring their case.
• GetBytes(Charset) Encodes the Charset string into a new array of bytes.
• IndexOf(SearchFor) Returns the index of the first occurrence of SearchFor in the string. The index is 0 based.
Returns -1 if no occurrence is found.
• IndexOf2(SearchFor, Index) Returns the index of the first occurrence of SearchFor in the string. Starts searching
from the given index. The index is 0 based. Returns -1 if no occurrence is found.
• LastIndexOf(SearchFor) Returns the index of the first occurrence of SearchFor in the string. The search starts at
the end of the string and advances to the beginning. The index is 0 based. Returns -1 if no occurrence is found.
• LastIndexOf2(SearchFor) Returns the index of the first occurrence of SearchFor in the string. The search starts at
the given index and advances to the beginning. The index is 0 based. Returns -1 if no occurrence is found.
• Length Returns the length, number of characters, of the string.
• Replace(Target, Replacement) Returns a new string resulting from the replacement of all the occurrences of
Target with Replacement.
• StartsWith(Prefix) Returns True if this string starts with the given Prefix.
• Substring(BeginIndex) Returns a new string which is a substring of the original string. The new string will
include the character at BeginIndex and will extend to the end of the string.
• Substring2(BeginIndex, EndIndex) Returns a new string which is a substring of the original string. The new
string will include the character at BeginIndex and will extend to the character at EndIndex, not including the last
character. Note that EndIndex is the end index and not the length like in other languages.
• ToLowerCase Returns a new string which is the result of lower casing this string.
• ToUpperCase Returns a new string which is the result of upper casing this string.
• Trim Returns a copy of the original string without any leading or trailing white spaces.
String concatenation
The concatenation character to join Strings is: &
Rasure B. B Page 1
Mobile Application Development
Examples:
• Strings Private MyString As String MyString = "aaa" & "bbb" & "ccc" result: aaabbbccc
• String and number MyString = "$: " & 1.25 result: $: 1.25
• String and variable, it can be either another string or a number. Private Val As Double Val = 1.25
MyString = "$: " & Val result: $: 1.25
String Interpolation
Smart strings can hold zero or more placeholders with code. The placeholders can be easily formatted. A placeholder
starts with $[optional formatter]{ and ends with }:
Log($"5 * 3 = ${5 * 3}"$) '5 * 3 = 15
You can put any code you like inside the placeholders.
Dim x = 1, y = 2, z = 4 As Int Log($"x = ${x}, y = ${y}, z = ${Sin(z)}"$) 'x = 1, y = 2,
z = -0.7568024953079282
Files
This window allows you to add (or remove) images to be shown on the layout :
Add Images: Allows you to select an image anywhere on your development computer. The
selected files will be copied to the Files folder of the current project. Once added, you can add
an ImageView to your layout and select the required image in the Image file property.
Selecting Files: Either click the checkboxes or right-click and select all or none.
Remove Selected: shows the following dialog:
Rasure B. B Page 2
Mobile Application Development
Yes: removes the selected files from the list and from the Files folder of the project. Make
sure to have a copy of the files you remove, because they are removed from the Files folder,
but not transferred to the recycle bin. This means they are definitively lost if you don’t have
a copy.
No: removes the selected files from the list but does not delete them from the project’s Files
folder.
Many applications require access to a persistent storage. The two most common storage types are files and
databases.
Android and iOS have their own file system. B4A nor B4i programs have access to files in the Windows system.
To add files to your project you must add those in the IDE in the Files Tab. These files will be added to the project
Files folder.
File object
The predefined object File has a number of functions for working with files.
File 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.
It's the Files folder in the project folder.
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.
B4A only
File.DirInternal / File.DirInternalCache These two folders are stored in the main memory of the device 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 Use this folder only if you really need it. The storage card root folder. In most cases this is
an internal storage card and not an external SD card. 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.
External storage.
You should use the RuntimePermissions library to get the best folder with:
MyFolder = RuntimePermissions.GetSafeDirDefaultExternal(SubFolder As String)
Returns the path to the app's default folder on the secondary storage device.
The path to File.DirInternal will be returned if there is no secondary storage available.
It is a better alternative to File.DirDefaultExternal.
Rasure B. B Page 3
Mobile Application Development
Starting from Android 4.4 it is no longer possible to directly access external storages. The only way to access these
storages is through the Storage Access Framework (SAF), which is a quite complex and under-documented
framework.
The ExternalStorage class makes it simpler to work with SAF.
Usage: 1. Call ExternalStorage.SelectDir. This will open a dialog that will allow the user to select the root folder.
Once selected the uri of the root folder is stored and can be later used without requiring the user to select the folder
again. Even after the device is booted. 2. Wait For the ExternalFolderAvailable event. Now you can access the files
under Storage.Root, including inside subfolders. 3. Files are represented as a custom type named ExternalFile. 4. The
following operations are supported: ListFiles, Delete, CreateNewFile, FindFile, OpenInputStream and
OpenOutputStream. See the attached example. Depends on: ContentResolver and JavaObject libraries. Add:
#AdditionalJar: com.android.support:support-core-utils
Rasure B. B Page 4
Mobile Application Development
- Takes a map object which holds pairs of key and value elements and stores it in a text file. The file format is known
as Java Properties file: .properties - Wikipedia, the free encyclopedia The file format is not too important unless the
file is supposed to be edited manually. This format makes it easy to edit it manually. One common usage of
File.WriteMap is to save a map of "settings" to a file.
File.ReadMap (Dir As String, FileName As String) As Map
- Reads a properties file and returns its key/value pairs as a Map object. Note that the order of entries returned might
be different than the original order.
File.WriteBytes (Dir As String, FileName As String, Data As Byte())
- Writes the given text to a new file.
Initializing a Canvas
When we initialize the Canvas, we must specify which view or bitmap it can draw onto. The simplest case
is to draw onto the Activity background:
Dim Canvas1 As Canvas
Canvas1.Initialize(Activity)
Then we can draw onto the Canvas:
Canvas1.DrawLine(0, 0, 100dip, 200dip, Colors.Red, 3dip)
Rasure B. B Page 5
Mobile Application Development
When our drawing is complete, we make the Canvas draw itself onto its target by making the target
invalid:
Note the first four parameters of DrawLine are in the order left, top, right, bottom.
When the Canvas is initialized and set to draw on a view, a new mutable bitmap is created for that view
background, the current view’s background is first copied to the new bitmap and the Canvas is set to draw
on the new bitmap. In this way, we can prepare our drawing over the top of the old background.
Canvas drawings are not immediately updated on the screen. You should call the target view Invalidate
method to make it refresh the view. This is useful as it allows you to make several drawings and only
refresh the display when everything is ready.
The Canvas can be temporarily limited to a specific region (and thus only affect this region). This is done
by calling ClipPath. Removing the clipping is done by calling RemoveClip.
You can get the bitmap that the Canvas draws on with the Bitmap property.
This is an Activity object; it cannot be declared under Sub Process_Globals.
Draws a circle with left edge of x and top of y. It can be filled with a given color and, if filled, the perimeter
can be outlined with a stroke of a given width.
Sub Globals
Dim cvsActivity As Canvas
Dim btnTest As Button
End Sub
Sub Activity_Create(FirstTime As Boolean)
End Sub
Sub Activity_Resume
' create a button
btnTest.Initialize("btnTest")
Activity.AddView(btnTest,10dip, 240dip, 200dip, 50dip)
btnTest.Text = "Draw Another Circle"
' initialize the canvas
cvsActivity.Initialize(Activity)
' draw a horizontal line
cvsActivity.DrawLine(20dip, 20dip, 160dip, 20dip, Colors.Red, 3dip)
' draw an empty rectangle
Dim rect1 As Rect
rect1.Initialize(50dip, 40dip, 150dip, 100dip)
cvsActivity.DrawRect(rect1, Colors.Blue, False, 3dip)
Rasure B. B Page 7
Mobile Application Development
Sub btnTest_Click
cvsActivity.DrawCircle(100dip, 40dip, 30dip, Colors.Green, False, 3dip)
' make the drawing visible
Activity.Invalidate
End Sub
***************************************END*****************************************
****
Rasure B. B Page 8