Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 6-MAD

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Mobile Application Development

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.

Note: The string functions are case sensitive.


If you want to use case insensitive functions you should use either ToLowerCase or ToUpperCase.
Example: NewString = OriginalString.ToLowerCase.StartsWith("pre")

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

Don’t confuse with VB syntax:


MyString = "aaa" + "bbb" + "ccc"
This doesn’t work!

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

On Android 4.4+ no permission is required to access this folder.


SubFolder - A sub folder that will be created for your app. Pass an empty string if not needed.
Acces a file in external stroge devices has become cumbersome in Android.
Erel has written a Class ExternalStorage - Access SD cards and USB sticks to ‘simplify’ the access.
Extract from Erels thread:
Before we start: 1. External storage means a real sd card or a connected mass storage USB device. 2. It has nothing
to do with File.DirRootExternal / DirDefaultExternal which actually point to an internal storage. 3. It has nothing to
do with runtime permissions. 4. You can use RuntimePermissions.GetAllSafeDirsExternal to directly access a
specific folder on the SD card. 5. The minimum version for this class is Android 5. It might work with Android 4.4
(change minSdkVersion if you like to try it).

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

File exists ? B4A, B4i, B4J


To check if a file already exists use:
File.Exists ( Dir As String, FileName As String)
Returns True if the file exists and False if not.
Note: File.Exists does not work with File.DirAssets !!!

Common methods B4A, B4i, B4J


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, it must be opened.
File.OpenOutput (Dir As String, FileName As String, Append As Boolean)
- Opens the given file for output, the Append parameter tells whether the text will be added at the end of the existing
file or not. If the file doesn't exist it will be created.
File.OpenInput (Dir As String, FileName As String)
- Opens the file for reading.
File.WriteString (Dir As String, FileName As String, Text As String)
- Writes the given text to a new file.
File.ReadString (Dir As String, FileName As String) As String
- Reads a file and returns its content as a string.
File.WriteList (Dir As String, FileName As String, List As List)
- Writes all values stored in a list to a file. All values are converted to string type if required. Each value will be
stored in a separare line. Note that if a value contains the new line character it will saved over more than one line and
when you read it, it will be read as multiple items.
File.ReadList (Dir As String, FileName As String) As List
- Reads a file and stores each line as an item in a list.
File.WriteMap (Dir As String, FileName As String, Map As Map)

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.

File.ReadBytes (Dir As String, FileName As String)


- Reads the data from the given file.
Returns: Byte()
File.Copy (DirSource As String, FileSource As String, DirTarget As String, FileTarget As String)
- Copies the source file from the source directory to the target file in the target directory.
Note that it is not possible to copy files to the Assets folder.
File.Copy2 (In As InputStream, Out As OutputStream)
- Copies all the available data from the input stream into the output stream.
The input stream is automatically closed at the end.
File.Delete (Dir As String, FileName As String)
- Deletes the given file from the given directory.
File.ListFiles (Dir As String) As List
- Lists the files and subdirectories in the diven directory.
Example:
Private List1 As List
List1 = File.ListFiles(File.DirInternal)
List1 can be declared in Sub Globals
File.Size (Dir As String, FileName As String)
- Returns the size in bytes of the specified file.
This method does not support files in the assets folder.
File.MakeDir (Parent As String, Dir)
- Creates the given folder (creates all folders as needed).
Example:
File.MakeDir(File.DirInternal, "music/90")

Graphics and Drawing


Canvas object
To draw graphics, we normally use a Canvas object. A Canvas is an object that draws on other views or
editable (also called “mutable”) bitmaps

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.

A Canvas can draw onto the following views:


Activity, ImageView, Panel and Bitmap
A bitmap must be “mutable” in order for a Canvas to draw upon it.
Most common Canvas functions
See the Canvas object for details.
DrawBitmap (Bitmap1 As Bitmap, SrcRect As Rect, DestRect As Rect)
Draws a source bitmap (or part of it) onto a destination. If the source and destination sizes are different,
the destination drawing is stretched or shrunk.
(Bitmap1 As Bitmap, SrcRect As Rect, DestRect As Rect,
DrawBitmapRotated
Degrees As Float)
Same functionality as DrawBitmap, but with a rotation around the centre of the bitmap.
(x As Float, y As Float, Radius As Float, Color As Int, Filled As Boolean,
DrawCircle
StrokeWidth As Float)
Rasure B. B Page 6
Mobile Application Development

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.

DrawColor (Color As Int)


Fills the whole view with the given color. The color can be Colors.Transparent making the whole view
transparent.
(x1 As Float, y1 As Float, x2 As Float, y2 As Float, Color As Int,
DrawLine
StrokeWidth As Float)
Draw a straight line from (x1,y1) to (x2,y2) with specified color and stroke width (in dips).
DrawRect (Rect1 As Rect, Color As Int, Filled As Boolean, StrokeWidth As Float)
Draw a rectangle with given size, color, whether filled, and line width.
(Rect1 As Rect, Color As Int, Filled As Boolean, StrokeWidth As
DrawRectRotated
Float, Degrees As Float)
Same as DrawRect, but rotated by the given angle
(Text As String, x As Float, y As Float, Typeface1 As Typeface, TextSize
DrawText
As Float, Color As Int, Align1 As Align)
Draws the given text in the given typeface, size and color.
Align1 is the alignment relative to the chosen position, and can have one of the following values: LEFT,
CENTER, RIGHT.

(Text As String, x As Float, y As Float, Typeface1 As Typeface,


DrawTextRotated
TextSize As Float, Color As Int, Align1 As Align, Degree As Float)
Same as DrawText, but with the text rotated.
Full details of all Canvas methods can be found here.
Example Program
In this example, we draw some sample shapes on the Main Activity. We put the code in the Sub
Activity_Resume because this is always run whenever the app starts or restarts. Thus, we do not need to
call Activity.Invalidate. We also add a button and draw a circle when it is pressed. In this case, we
need to call Activity.Invalidate so that the Canvas will be transferred to the Activity’s background.

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

' draw an empty circle


cvsActivity.DrawCircle(50dip, 200dip, 30dip, Colors.Green, False, 3dip)
' draw a text
cvsActivity.DrawText("Test text", 50dip, 150dip, Typeface.DEFAULT, 20, Colors.Yellow,
"LEFT")
' draw a filled circle with a boarder
cvsActivity.DrawCircle(50dip, 340dip, 30dip, Colors.Green, True, 3dip)
' the above will always be drawn because
' the Activity is automatically redrawn on activity_resume
End Sub

Sub btnTest_Click
cvsActivity.DrawCircle(100dip, 40dip, 30dip, Colors.Green, False, 3dip)
' make the drawing visible
Activity.Invalidate
End Sub

The resulting screen is:

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

Rasure B. B Page 8

You might also like