Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Hello B4A: Develop Native Android Apps using Visual Basic Syntax

4.35/5 (10 votes)
8 Nov 2016CPOL19 min read 34.5K   554  
Using Basic4Android, develop your first Android Native App

Introduction

Thank you for showing interest in my article. You can imagine my awe when I discovered this. So I can use my Visual Basic experience to develop Android Apps!!! I had already taken the route of learning Java and creating the XML files, however I found it a little tedious at times to say the least. I guess it was just being scared of the unknown. I wanted an easier way out. I wanted a quick way out. I was running towards a deadline, a deadline I set for myself anyway. At the end of it, the result was a free app called Bible.Show, available in the Android Play Store. You can check it out here.

Today I will show you how you can create and develop a Native Android App, that you can install in your device with your own icon, own app name with no xml and no java, but pure visual basic syntax.

A couple of days ago, I posted an article here on how to develop java apps using visual basic syntax. Please go through it first as the approach is exactly the same here.

Step 1: Let's set up the development environment

The IDE (Intergrated Development Environment) you will be using is called B4A (Basic4Android) from Anywhere Software. At the time of writing, this software only works on a Windows running computer. Let's do this.

1.1 Download and install the Java JDK. Accept the license agreement and select the appropriate version of the JDK whether x86 or Windows 64 version.

1.2 Download and install the Android SDK. The android sdk does not usually work well with a path with spaces like "Program Files", then please install it for example on "c:\android-sdk". Select to install API 23 or Android 6.0, SDK Tools, platform tools, google usb driver, android support repository, Google repository at least.

Figure 1: Android SDK Manager

Image 1

1.3 Download and install the B4A Trial. This is a 30 day trial of the IDE. It will be enough for this exercise and other apps you will create during that time.

Figure 2: Running B4A

Image 2

  • Create a folder on our c drive, for example name it b4A. Inside that folder create two subfolders, one called Shared and the other called Libraries.
  • So you will have c:\b4a and c:\b4a\Shared and c:\b4a\Libraries.
  • Start B4A, goto Tools > Configure Paths and set up your paths.

Figure 3: B4A Configure Paths

Image 3

  • javac.exe - You will need to set up javac.exe from the Java JDK folder you installed at.
  • android.jar - This will reside on your android sdk install path, in the example here we used c:\android-sdk
  • additional libraries - Point this to c:\b4a\libraries as per example or whatever folder you opted for for additional libraries. Think of additional libraries as DLLs (dynamic link libraries in Visual Basic Terminology). Libraries in java are .jar files with their xml documentation.
  • shared modules - point this to c:\b4a\shared as per example or whatever folder you opted to create for shared folders. Think of modules as .bas files in Visual Basic, also here they have a .bas extension with code that can be accessible anywhere within your app.

1.4. Download and Install an Droid4X Emulator (Optional). I have found this emulator to be fast and easy to use. You use an emulator to test your apps before you can deploy them to your device and even the Android Play Store. You can also try Genymotion. If you decide to use Genymotion, you can see my article here on how to ready it for your environment. In droid4x emulator you can drag and drop your apks to install them.

Figure 4: Droid4X Emulator

Image 4

1.5 Get your Android Device ready for Development

To be able to get your Android Device ready for testing and debugging your apps you need to enable USB debugging in it. Starting from Android 4.2 the Development menu is hidden. In order to reveal it you should follow these instructions:

  • Choose Settings - About Phone
  • Find the Build Number entry and click on it 7 times.

You can also see this article on how to enable usb debugging. You will also have to also enable "install from unknown sources". This is due to the fact that the app you will develop will be "unknown", not from the Google Android Store yet. I have found that an app called Synios has been very friendly to take screenshots from my device and also confirm if usb connection to my computer is done properly.

Figure 5: Device connected to the free Syncios app via USB

Image 5

1.6 Install B4A Bridge on your Android Device (Optional)

Figure 6: B4A Bridge on Google Play Store

Image 6

The B4A bridge is used for getting your Android device connected to your development environment. It also allows one to see how their apps will look like in design mode as it also installs a B4A designer. This is optional as it does not hinder anyone from developing their apps. This bridge works on a wireless network, so your device and your computer should be on the same network.

To get your device connected with B4A Bridge, Start Wireless on the B4A Bridge App, an IP address will be provided, take this down. In the B4A IDE on your computer, goto Tools > B4A Bridge > Connect > New IP and type in the IP provided by B4A Bridge.

Figure 7: B4A Bridge on Device

Image 7

As earlier indicated, the B4A Bridge is an optional step as you can just connect your Android device to your computer for your app development. In summary, the following crucial steps should be undertaken for your IDE to be ready for Android App Development.

  • Install Java SDK
  • Install Android SDK
  • Install B4A Trial
  • Set B4A Paths
  • Enable USB Debugging on your Android Device

If you have completed these steps, congratulations, you are ready for your first Android App.

Step 2: Writing Code for your Android App

In this step we will take a look at the code that gets created each time you create a new project in the B4A development environment.

In the IDE follow these instructions.

  • Click on File > New, the code area will be updated with a new project structure
  • Click on File > Save, you had earlier created a folder called c:\b4a, goto to that folder
  • Click 'New Folder' and type in HelloB4A to create a new folder within the c:\b4a folder. This means you will now have c:\b4a\HelloB4A
  • In the 'File Name', type in HelloB4A and click Save.

Your project is now ready. Let's take a look at the project structure as depicted in Figure 8 below.

Figure 8: B4A HelloB4A Project Structure

Image 8

A new project file called HelloB4A.b4a has been created. On the IDE, this contains all the code that is sitting in the Main module. For this exercise we will not look at the Starter module. Let me explain the structure also

  • Files - this will host any files to be used by your app. These could be text files, your icon for your app etc.
  • Objects - this contains the binary and java generated files for your app. Your apk will be found there after compilation in Release mode.

All projects that you will create will follow this same fashion. Now, lets please look at the code.

VB.NET
#Region  Project Attributes 
 #ApplicationLabel: B4A Example
 #VersionCode: 1
 #VersionName: 
 'SupportedOrientations possible values: unspecified, landscape or portrait.
 #SupportedOrientations: unspecified
 #CanInstallToExternalStorage: False
#End Region

This code is denoted by a Region identifier. The region here is Project Attributes. You can collapse and expand a region by clicking on the plus or negative sign in its opening.

  • ApplicationLabel - this will be the name of your app. You can change this to be HelloB4A for example.
  • VersionCode - this is the version of your app, 1, 100, 200 etc
  • VersionName - this is the version name of your app, for example, version code 100 might mean 1.0.0.
  • SupportedOrientations - the orientations for your app, landscape, portrait etc. You can specify both here, separated by commas. If you have specified portrait, your app will only display in that mode ONLY, same with landscape.
  • CanInstallToExternalStorage - usually this is false. When set to True it means your app can install to external SD cards or can even be moved to external storage.

I have color coded ApplicationLabel as it is the main attribute here to identify your app with its name. That is the name that will be displayed on your devices springboard/dashboard. You can also indicate the unique name that your app will be identified with on the play store. To do that...

Goto Project > Build Configurations, Figure 9 will appear

Figure 9: Build Configuration

Image 9

Change the package to be com.YourName.HelloB4A and replace YourName with your actual name or company name. Click Ok.

I like to think of these names like:

  • com - its a commercial application
  • YourName - your company name. Your company or yourself can have a lot of apps
  • HelloB4A - this is the name of this app from your yourself/company.

Here is the updated Build Configuration as shown with Figure 10.

Figure 10: Updated Build Configuration

Image 10

For now, you have given your app a unique name for the play store with Build Configuration, also specified the name of your app for your dashboard, now let's give your app an icon. To give your app an icon that will show on your device, you can use a png, jpeg, but it should have proper dimensions. Try to stick to 64px X 64px for the icon. I have found our that anything bigger crashes your app. You can also try 80px X 80px, i.e. the width and the height of your icon.

For your icon, goto Project > Choose Icon. Select your icon from the folder that you have saved it in. Remember the dimensions of your icon should be proper please. That's it. Now you are ready to finalize your code. The code in Main is the basic code that will make your app work.

VB.NET
#Region  Project Attributes 
 #ApplicationLabel: HelloB4A
 #VersionCode: 100
 #VersionName: 1.0.0
 'SupportedOrientations possible values: unspecified, landscape or portrait.
 #SupportedOrientations: portrait
 #CanInstallToExternalStorage: False
#End Region

Above are the updated Project Attributes for this example.

VB.NET
#Region  Activity Attributes 
 #FullScreen: False
 #IncludeTitle: True
#End Region

Each screen/form in B4A just like Android programming is called an Activity. You can move from one activity to another using a method called StartActivity(otherActivityName). For this exercise we will not have multiple screens.

  • FullScreen : False - here we are indicating that the screen/form should not be full screen. Full screens take the whole area of the device including the area that shows the time, battery levels etc. Setting this to False means that the top area of your screen should appear.
  • IncludeTitle : True - here we are indicating that the screen should have a Title area. You can set your screen title to be "HelloB4A" inside the Activity_Create method.
VB.NET
Sub Process_Globals
 'These global variables will be declared once when the application starts.
 'These variables can be accessed from all modules.
End Sub

The Process_Globals method is where you can also define your variables. This will be similar to the visual basic syntax e.g.

VB.NET
Dim strA As String
Dim boolX As Boolean
Dim intY As Int
Dim dblZ As Double
Dim strArray() As String
Dim m As Map
Dim l As List
Dim lstView As ListView

Dont worry about the Map, List, ListView variables for now. I was just using that for demonstration. You can also change your Dim to be Private or Public.

VB.NET
Sub Globals
 'These global variables will be redeclared each time the activity is created.
 'These variables can only be accessed from this module.
End Sub

As indicated in the comments, any variables declared inside Sub Globals will be private to the Main Module. Now lets look at the entry point of your screen. In VB its like the code that runs on frm.Show event.

VB.NET
Sub Activity_Create(FirstTime As Boolean)
 'Do not forget to load the layout file created with the visual designer. For example:
 'Activity.LoadLayout("Layout1")
 Msgbox("Welcome to B4A!", "")
End Sub

In my previous article, I explained what LoadLayout did, we will however look at that later here. In this particular case, when the screen is shown in your device, we want a messagebox with Welcome to B4A! to be shown. Ok, let's continue.

VB.NET
Sub Activity_Resume
'runs when your app comes out of pause /background state
End Sub

On Activity_Resume, you can put any code that you want to be ran when your app comes out of sleep mode. Sleep mode is when your app goes to the background. As an example, you can restore saved screen size in this method.

VB.NET
Sub Activity_Pause (UserClosed As Boolean)
'runs when your app goes into sleep / background / pause state
End Sub

On Activity_Pause, you can put any code that you want to be ran when your app goes to sleep. This can be code that could be related to screen settings for example that you want to be saved and will be restored with Activity_Resume.

Go on, click Run in the IDE to run your app with your usb-debugging on, install from unknown sources Android device connected to your computer.

Figure 11: Run HelloB4A App

Image 11

The compilation process will run as depicted in Figure 12 below and your app will be installed in your device.

Figure 12: Compilation Process

Image 12

The compilation process generates a resource file from your project, converts your code to java and then generates your APK file to distribute. If you take a peek again in your project folder, inside the objects folder, you will find it updated as depicted with Figure 13 below.

Figure 13: Project Objects Folder Updated

Image 13

One should not use, dots or anything special in the ApplicationLabelName as it will result in the apk name being result.apk. The APK file is the only file that you distribute or upload to the Android Stores and nothing else. Figure 14 is what should be appearing on your device. If you had Droid4X running in the same Wifi, on compilation you will be provided with a prompt to select which device to install your app in.

Figure 14: HelloB4A App Running on Device.

Image 14

Click Ok on your device and click the back button, this should take your app to the background. In your device dashboard, you should see your app, in my example in a yellow rectangle.

Figure 15: HelloB4A on Device Dashboard

Image 15

Now, if you have been able to get to this part, you have done very well and managed to

  • Set up your development environment properly
  • Set up your device for development purposes
  • Developed your first Native Android App, gave it a unique name and got it installed on your device.

Congratulations!!!

Creating Screens

From the above introduction, I have been able to demonstrate how one can develop a Native Android App using Visual Basic Syntax. It is a simple example just to get the ball rolling. In this next part we will create a screen for a user to enter input, a button to process that input etc. My previous article introduced you to Java programming with Visual Basic Syntax using B4J (Basic4Java). This article is delving on B4A (Basic4Android).

You might have noted that the IDE for B4A looks similar to the B4J IDE including the code area too and other functionalities. Too here will create a screen using a designer, link it with LoadLayout, link its events with Generate Members etc.

With the Main module selected, then from the IDE menu, click Designer, Figure 16 should appear.

Figure 16: B4A Layout Designer

Image 16

The built in controls for B4a are:

  • AutoCompleteEditText - text with combobox like functionality
  • Button - click a button
  • CheckBox - a simple checkbox
  • EditText - enter input
  • HorizontalScrollView - swipe left and right control
  • ImageView - display images
  • Label - display text
  • ListView - list items in scrollable view port
  • Panel - host other controls inside a panel
  • ProgressBar - show progress of an event
  • RadioButton - option button
  • ScrollView - swipe up and down control
  • SeekBar - slider control
  • Spinner - combobox
  • TabHost - tabs that host other controls inside
  • ToggleButton - switch with On/Off
  • WebView - display html content
  • CustomViews - these are controls that you can create or created by other users using classes.

Let's create a simple form for a user to enter text. This should look like Figure 17 below.

Figure 17: frmSpeak Layout

Image 17

To do this, goto

1. Add View > Label. Drag the control to be placed as displayed on the form. Change the properties to Name: lblName, HorizontalAnchor: Both, Text: Text2Speech. To set the anchors, first select the Label and drag the handles for the control to be at the edge of the screen and then change the Anchor. You need to do that in that order as anchors are saved. This is important. Place your controls first and then anchor them.

2. Add View > EditText. Drag the control to be placed as displayed on the form. Change the properties to Name: txtWords, HorizontalAnchor: Both, VerticalAlignment: Top, Leave the InputType: Text, you can have password, number etc as an input type, Hint: Words to Speak and Wrap: Checked.

3. Add View > Button. Drag the control to be placed as displayed on the form. Change the properties to Name: cmdSpeak, HorizontalAnchor: Both, VerticalAnchor: Bottom, Text: SPEAK

What do anchors do? Anchors ensure that your control is stretched or compressed depending on what you have specified. When HorizontalAnchor is Both, it means the control should be stretched both left and right to fit the area of your screen, whether small or big. When VerticalAnchor is Bottom is means the control should be moved to the bottom of the screen no matter what size the device is. For the txtWords control, we want it to be stretched left and right and also stretched to the bottom just above the cmdSpeak button.

4. Click File > Save on the designer to save your layout, I have given it a name of frmSpeak.

What we have done so far is create a screen with a label, input text and a button. We want the app to do a text to speech reading for anything typed in txtWords control. A hint will be provided to the user on txtWords.

Linking the layout/screen controls to Source Code

To link the layout controls to the code, on the Designer, we need to generate the members first. We want to access the content of txtWords and trap the cmdSpeak Click event. In Figure 18, accessible via Tools > Generate Members, check cmdSpeak and also its Click event, also check lblNote and txtWords.

Figure 18: frmSpeak - Generate Members

Image 18

Click the Generate Members button. This will add the control references to your code area in Main. You should be careful when generating members that you have the code module that the members will be generated into first. First open the module and then generate the members. Close the designer, now back in the code, notice the changes.

Sub Globals has now been changed to

VB.NET
Sub Globals
 'These global variables will be redeclared each time the activity is created.
 'These variables can only be accessed from this module.
 Private cmdSpeak As Button
 Private txtWords As EditText
 Private lblNote As Label
End Sub

Also, a new method has been added

VB.NET
Sub cmdSpeak_Click 
End Sub

To show your new screen, goto Activity_Create and change it to be:

VB.NET
Sub Activity_Create(FirstTime As Boolean)
 ' show the frmSpeak screen when the app starts
 Activity.LoadLayout("frmSpeak")
 'change the screen title to be Text2Speech
 Activity.Title = "Text2Speech"
End Sub

If you run the app now, after installing on your device, this is what should show depicted with Figure 19 below.

Figure 19: Text2Speech screen display

Image 19

Update the code in Main to be like this...

VB.NET
Sub Activity_Create(FirstTime As Boolean)
 ' show the frmSpeak screen when the app starts
 Activity.LoadLayout("frmSpeak")
 'change the screen title to be Text2Speech
 Activity.Title = "Text2Speech"
 ' change the text for the label to be Status...
 lblNote.Text = "Status..."
End Sub

And the cmdSpeak_Click

VB.NET
Sub cmdSpeak_Click
 ' display the contents of txtWords in debug log
 Log(txtWords.Text)
 ' if the button text is speak, change its text to stop and the note to be Speaking
 ' if the button text is stop, change it to speak
 If cmdSpeak.Text = "SPEAK" Then
  lblNote.Text = "Speaking..."
  cmdSpeak.Text = "STOP"
 Else
  lblNote.Text = "Stopped Speaking..."
  cmdSpeak.Text = "SPEAK"
 End If
End Sub

Run the app again, and click the Speak button, it will toggle the content of the label and also of the button. With that I have just shown you a simple If Then Else statement in the working. What this does is, if the button text is SPEAK, change it to STOP and if its STOP change it to SPEAK. With that change the note caption too.

Congratulations, you have just completed your second Android App with screens, buttons, labels and all. As you have already figured out, this example is about Text2Speech. So far we have not added anything like that. Let's make our app to be able to speak the text we have entered in txtWords. To be able to do that we need a library for text to speech.

Adding Libraries (what VB called DLLs)

In the IDE menu, select Windows > Reset, then select Libraries in the right bottom navigation bar. From the selected list select TTS. If you dont have TTS listed, you can get it from the attachment and save it in your c:\b4a\Shared folder. If you copy it there, on the libraries listing, right click on it and select Refresh and then select it again to be loaded on your project.

Figure 20: Libraries loaded to the project

Image 20

After you have loaded the Library, change your code to be like this.

VB.NET
Sub Process_Globals
 'These global variables will be declared once when the application starts.
 'These variables can be accessed from all modules.
 Dim TTS1 As TTS
End Sub

We declared a TTS object named TTS1 as a process global object. This references the TTS library just loaded.

VB.NET
Sub Activity_Create(FirstTime As Boolean)
 ' show the frmSpeak screen when the app starts
 Activity.LoadLayout("frmSpeak")
 'change the screen title to be Text2Speech
 Activity.Title = "Text2Speech"
 ' change the text for the label to be Status...
 lblNote.Text = "Status..."
 txtWords.Text = "This is my first Native Android App developed with Basic4Android!"
End Sub

We are changign the txtWords content to be as specified above. Remember, on that EditText, you can type your text and press the cmdSpeak button too. Let's add the following code...

VB.NET
Sub TTS1_Ready (Success As Boolean)
    If Success Then
        'enable all views
        For i = 0 To Activity.NumberOfViews - 1
            Activity.GetView(i).Enabled = True
        Next
        cmdSpeak_Click 'play first sentence
    Else
        Msgbox("Error initializing TTS engine.", "")
    End If
End Sub

The Ready event of the TTS object is raised when the text to speech engine is ready. As we have defined our TTS as TTS1 we link that event to that object. What this routine does is to enable all controls on the form by turning their Enabled Status to True. For example in the Designer, you can change the Enabled property of the cmdSpeak button to False. After all the controls are enabled, the cmdSpeak_Click event is fired.

VB.NET
Sub Activity_Resume
 If TTS1.IsInitialized = False Then
        TTS1.Initialize("TTS1")
    End If
End Sub

In Sub Activity_Resume we check if the TTS1 object is initialized and if not we initialize it. Then we release the TTS1 object when the app goes to the background.

VB.NET
Sub Activity_Pause (UserClosed As Boolean)
 TTS1.Release
End Sub
VB.NET
Sub cmdSpeak_Click
 ' display the contents of txtWords in debug log
 If txtWords.Text.Length > 0 Then
  TTS1.Speak(txtWords.Text, True)
        txtWords.SelectAll
 End If
 ' if the button text is speak, change its text to stop and the note to be Speaking
 ' if the button text is stop, change it to speak
' If cmdSpeak.Text = "SPEAK" Then
'  lblNote.Text = "Speaking..."
'  cmdSpeak.Text = "STOP"
' Else
'  lblNote.Text = "Stopped Speaking..."
'  cmdSpeak.Text = "SPEAK"
' End If
End Sub

As might have noticed, libraries are other .jar and .xml files that are developed to work with the B4A framework. There are a variety of those available as some other B4A programmers have written them and others coming from the framework itself.

Go on, run your app, let it install on your device and play around with it. For now we are done.

You can also run your app in Debug mode where you can check it for errors. In Release mode, B4A will create the apk for you which you can find in the Objects folder. Your final app should look like this Figure 21.

Figure 21: Final App

Image 21

Points of Interest

This article at first touches on how you can set up your development environment for B4A, then run your first Android app, write some code to make your app behave in different ways using an if statement and then add a library which is an advanced feature. It also explores the Activity_Pause and Activity_Resume event of your screen. Added for the library is the Ready event of the TTS library. It also touched on initializing objects. I have tried then to touch on basic easy functionalities that one can do and also on the more complex functions to demonstrate the power of this framework.

The trial version of B4A does not work with Libraries and to do that you will need a paid version and the size of your apk will be limited. You can visit the B4X website here to get a paid version.

Whilst the syntax is almost identical to visual basic, there are some new methods, constants and other definitions that one can learn along the way. It's a very interesting rabbit hole anyway for anyone interested in doing things B4A. The other nice thing is there is a support forum for anything for this framework.

When you run the final app, the TTS engine might take a while to initialize, perhaps a second or two, please be a little patient.

Enjoy.

PS

  • Should you be interested in this world, you can download a Beginners Guide from here.
  • You can also get the User's Guide for more advanced feautures too.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)