Android Tutorial Collecting tips - Beginners wanted!

Status
Not open for further replies.
I want to collect useful tips for developers who are starting to develop with Basic4android.
I'm deeply familiar with Basic4android and therefore not always aware of difficulties that new users may encounter.
I would like to ask you to think for a moment about difficulties you encountered while getting started with Basic4android and write some tips that may help others who face the same difficulties.

Please start a new thread for any question. Only tips, examples and references should be posted here.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
First two tips:
- Compiler says: "Are you missing a library reference?". Go to the Libraries tab in the right pane and check the required libraries. If you do not know which library a specific object type belongs to, you can go to the documentation page. At the bottom of this page there is a long list with all the objects types. Pressing on any type will take you to the right library. Note that the trial version doesn't support libraries. Only the full version.
- When I try to compile / open 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.
 

kickaha

Well-Known Member
Licensed User
Longtime User
Two that got me early on:

If you add a view to a layout with designer, you should not initialise it in your code.

If you define a type that includes a variable that needs initialising (ie a List), you need to initialise the type variable, and then the included variable after definition, EG:
B4X:
   Type main (roundslist As List, roundselect As Int)
   Dim rounds As main 
   rounds.Initialize
   rounds.roundslist.Initialize
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
@kickaha, these two tips are excellent for new developers and exactly the purpose of this thread.
I want to add the common error of adding multiple references of the same object (usually arrays).
Bad example:
B4X:
Dim List1 As List
List1.Initialize
Dim arr(3) As Int
For i = 0 To 9
 arr(0) = i 'First index is always 0. This means that the last index is always arr.Length - 1
 arr(1) = i
 arr(2) = i
 List1.Add(arr) 'We are adding the array as a single item.
Next
Dim arr2() As Int 'Declare an empty array
arr2 = List1.Get(0) 'Get the first array added to the list. In this case the list holds 10 references to the SAME array.
Log(arr2(0)) 'Will print 9. NOT 0.
Good example:
B4X:
Dim List1 As List
List1.Initialize

For i = 0 To 9
 Dim arr(3) As Int 'Create a new array every iteration
 arr(0) = i
 arr(1) = i
 arr(2) = i
 List1.Add(arr) 'We are adding the array as a single item.
Next
Dim arr2() As Int 'Declare an empty array
arr2 = List1.Get(0)
Log(arr2(0)) 'Will print 0 as expected.
 

Jim Brown

Active Member
Licensed User
Longtime User
Mine's more of a "good programming practice". I know you mention in the docs that timers should be stopped when the activity pauses, but should accelerometers be stopped too?
I am thinking in terms of ensuring good behaviour from the app (0% CPU usage when paused)
B4X:
Sub Process_Globals
    Dim Accelerometer As PhoneAccelerometer
    Dim timer1 As Timer
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        timer1.Initialize("Timer1",20)
    End If
End Sub

Sub Activity_Resume
    Accelerometer.StartListening("Accelerometer")
    timer1.Enabled = True
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    Accelerometer.StopListening
    timer1.Enabled = False
End Sub

Another tip, I believe application icons should be 76x76. It might be worth mentioning somewhere. I am right about this dimension though?
 

moster67

Expert
Licensed User
Longtime User
Sender keyword

I find the Sender keyword very useful. Sender returns the object which raised an event.

It is very useful when you have an activity in which you have created many views of the same type (such as labels, panels, buttons) programatically. If you use Sender along with the object's tag property you can also obtain very easily the value of the object which triggered the event (as long as you assign it to the tag-property). Here is a great example which Klaus posted here on the forum:

From http://www.b4x.com/forum/basic4android-updates-questions/7462-control-sender.html
B4X:
Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
  Dim Map1 As Map
End Sub
 
Sub Activity_Create(FirstTime As Boolean)
  Dim i, col, row As Int

  Map1.Initialize
  For i = 0 To 14
    Dim Btn As Button
    Btn.Initialize("Buttons")
    Map1.Put("Button" & i, Btn)
    Btn.Tag = "Button" & i
    col = i Mod 5
    row = Floor(i/5)
    Activity.AddView(Btn,col*60,row*60,55,55)
  Next
End Sub
 
Sub Activity_Resume
End Sub
 
Sub Activity_Pause (UserClosed As Boolean)
End Sub
 
Sub GetButtonFromName(Name As String) As Button
  Dim b As Button
  b = Map1.Get(Name)
  Return b
End Sub
 
Sub Buttons_Click
  Dim Send As Button
  Send = Sender' sets the button that raised the event to Send
  Send.Text = Rnd(1,50)
  Msgbox(Send.Tag&" clicked","Buttons")
End Sub

Here is another example from Erel
(see http://www.b4x.com/forum/basic4android-getting-started-tutorials/8385-variables-objects-basic4android.html):
B4X:
Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    For i = 0 To 9 'create 10 buttons
        Dim Btn As Button
        Btn.Initialize("Btn")
        Activity.AddView(Btn, 10dip, 10dip + 60dip * i, 200dip, 50dip)
    Next
End Sub

Sub Btn_Click
    Dim b As Button
    b = Sender
    b.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub

You can use Sender for many things.
 

JMB

Active Member
Licensed User
Longtime User
The Life of a View

I'm pretty much a beginner, so here's something I learned regarding views and container views. I guess the experts may consider this stuff obvious, but it wasn't to me! :)

I was initially confused by the error thrown up by the following code:
B4X:
Dim pnlShow As Panel
pnlShow.Initialize("pnlShow")
pnlshow.Color=Colors.Yellow
pnlshow.SetLayout(2,3,200,30)
I got an error on the "SetLayout" line which I could not get my head round.

I did not realise that until you actually added this view to another view, you could not set positional information. I couldn't understand why I could set the color of the panel, but not it's position.

Thanks to the forums, I discovered that once you add the panel to an Activity or to an already "active" view, you can then set the positional data, as below:
B4X:
Dim pnlShow As Panel
pnlShow.Initialize("pnlShow")
pnlshow.Color=Colors.Yellow
Activity.AddView(pnlshow,2,3,200,30)   'Bring to life by adding to Activity
And now of course, you can change its layout any time you like in code.

The same thing applies to other views, for example the button view. This code gives an error on the line "btnTest.Left=3"
B4X:
Dim btnTest As Button
btnTest.Initialize("btnTest")
btnTest.Text="Press me"
btnTest.Left=3
This code gives the same error for the same reason - although the button view "exists" in memory, it has not been added to a container such as the Activity, or another "active" container view such as a panel, and so positional information is meaningless. The correct code is shown below:
B4X:
Dim btnTest As Button
btnTest.Initialize("btnTest")
btnTest.Text="Press me"
Activity.AddView(btnTest,3,50,76,76)   'Bring to life by adding to Activity
Hope this is of use. Lots more to learn - great thread!

JMB
 
Last edited:

wheretheidivides

Active Member
Licensed User
Longtime User
Tip. If on the programming screen, on the right window pane...if you click an item to remove a messgae pops up. it will ask if you want to delete it.....

If you say yes it deletes it off the hard drive.

if you say no, it removes it from the program and leaves it on the hard drive.


I lost tons of designer stuff because of this. Maybe you could have a second pop up explaining it will delete them off of hard drive.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Dates - Dates values are stored as the number of milliseconds since 1 January, 1970. This value is too large for an Int. It must be saved in a Long variable.
B4X:
Dim now As Long
now = DateTime.Now
Saving it in an Int variable will not throw any error. It will however represent a "random" date.
Hex notation - You can write values in base 16 by adding the prefix '0x':
B4X:
Dim i As Int
i = 0xabcd23
This is especially useful for colors. You can specify the four color components (alpha, red, green blue) as a 4 byte value with hex notation:
For example:
B4X:
Activity.Color = 0xFFFF0000 'Red
'Or:
Activity.Color = 0xFF800080 'Purple
 

gobblegob

Member
Licensed User
Longtime User
Read text file from External SD Card. very simple but could be helpful.
Folder SDCARD/Android/data/ your app name

B4X:
   Dim savedtext As String
   savedtext = File.ReadString(File.DirDefaultExternal, "mytextfile.txt")
 

gobblegob

Member
Licensed User
Longtime User
How to open a webpage with WebView.

1. add Webview to designer.
2. add button to designer.
3. generate members.

B4X:
         Button1_Click
      Dim UserURL As String
      UserURL = "http://www.google.com.au/"
                WebView1.LoadUrl(UserURL)
         End Sub

Hope this is helpful
 

gobblegob

Member
Licensed User
Longtime User
Write text to a text file to SD Card.
File saved to SDCARD/Android/data/ your com file name

B4X:
File.WriteString(File.DirDefaultExternal, "mytextfile.txt", "text to write")
 

prokli

Active Member
Licensed User
Longtime User
Two that got me early on:

If you add a view to a layout with designer, you should not initialise it in your code.

If you define a type that includes a variable that needs initialising (ie a List), you need to initialise the type variable, and then the included variable after definition, EG:
B4X:
   Type main (roundslist As List, roundselect As Int)
   Dim rounds As main 
   rounds.Initialize
   rounds.roundslist.Initialize


I would like to agree with kickaha!
It took me a couple of days to understand when to use "Initialize(...)" of any object (view) and when not! Views added by the designer are obviously pre-initialized objects and do not need to be explicitly initialized. A short hint within the tutorial would be nice for beginners.

Thanks
 

Harris

Expert
Licensed User
Longtime User
Begin / End Transaction when making SQL inserts/updates

Like the help file section declares: Using Begin/End transaction - along with TransactionSuccessful will GREATLY improve "writing" speed in SQL.
My code went from 12 seconds to milliseconds in writing records.


Simple example:
B4X:
SQL1.BeginTransaction
Try
    'block of statements like:
    For i = 1 to 1000
        SQL1.ExecNonQuery("INSERT INTO table1 VALUES(...)
    Next
    SQL1.TransactionSuccessful
Catch
    Log(LastException.Message) 'no changes will be made
End Try
SQL1.EndTransaction
 

Pfriemler

Member
Licensed User
Longtime User
Code conversion help and samples

I am all but a serious programmer, using MS VB3, VB6 and embeddedVB3 on WinMobile for some very special purposes, without any commercial background.

Although B4A looks like Basic, many of the available function requires different coding. Walking through the tutorials, you can learn much about what B4A can and does, but I miss a basic introduction to the commands. Maybe this will fill a book unwritten yet ...

Until this, it would be very helpfull to give some translation help like this article at this forum does - common used commands translated to B4A.

For example (this is from the linked text above, left=VB6, right=B4A)
B4X:
Dim b as Boolean:
If b then...        If b = True Then...  (You must have the "= True".)
a = a + b           If b = True Then a = a - 1
                       Boolean's value cannot be used in a math function in B4A.

ReDim Array()       Dim Array() -- to clear an array, just Dim it again.

Global Const x=1    Dim x As Int: x=1

Do [Until/While]    same
Loop [Until/While]  Loop  [Until/While not allowed.]
For - Next          same
Exit Do/For         Exit
If - Then - Else    same, except VB's ElseIf is "Else If" in B4A
Although, this file has to be edited and corrected. So
- an "if b then" is possible, as long b is a true boolean (but not like VB6 where any value except 0 is treated to be true)
- For-next: the loop variable must not given: "next i" leads to a compiler error
and so on.
 
Last edited:

derez

Expert
Licensed User
Longtime User
Dim b as Boolean:
If b then... If b = True Then... (You must have the "= True".)

This is wrong, if b is boolean then
B4X:
if b then...
works, you don't need the =true (it may still be used for clarity.
 

Pfriemler

Member
Licensed User
Longtime User
This is wrong, if b is boolean then
B4X:
if b then...
works, you don't need the =true (it may still be used for clarity.

It was a convenient way to shorten "if flag<>0 then" to "if flag then". But as I said two posts above:
"if b then" is possible, as long b is a true boolean (but not like VB6 where any value except 0 is treated to be true). For e.g. if b=4 this leads to a runtime exception: Cannot parse: 4 as boolean...

Nevertheless: in the example "if b = True then" b has to be a Boolean. In this case, "= True" is not necessary.


@aklisiewicz: I think, most of Basic4Android programmers do have any BASIC experiences...
 

agraham

Expert
Licensed User
Longtime User
not like VB6 where any value except 0 is treated to be true
The underlying Android Dalvik bytecode runtime and the Java language are strongly typed. Basic4android is actually also strongly typed "inside" but tries to accomodate some measure of automatic type conversion. For performance reasons it does not support things like converting an empty string to a zero for numeric operations or a zero to False for boolean operations. In concept Basic4android is more like VB.Net than VB6 as VB.Net sits upon a similar strongly typed runtime.
 
Status
Not open for further replies.
Top