1. *** New version of B4J is available ***
    B4J v7.8
    Dismiss Notice

Android Tutorial Collecting tips - Beginners wanted!

Discussion in 'Tutorials & Examples' started by Erel, May 9, 2011.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    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.
     
  2. Erel

    Erel Administrator Staff Member Licensed 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.
     
  3. kickaha

    kickaha Well-Known Member Licensed 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:
    Code:
    Type main (roundslist As List, roundselect As Int)
       
    Dim rounds As main 
       rounds.Initialize
       rounds.roundslist.Initialize
     
  4. Erel

    Erel Administrator Staff Member Licensed 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:
    Code:
    Dim List1 As List
    List1.Initialize
    Dim arr(3As 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:
    Code:
    Dim List1 As List
    List1.Initialize

    For i = 0 To 9
     
    Dim arr(3As 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.
     
  5. Jim Brown

    Jim Brown Active Member Licensed 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)
    Code:
    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?
     
  6. moster67

    moster67 Expert Licensed 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.basic4ppc.com/forum/basic4android-updates-questions/7462-control-sender.html
    Code:
    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 StringAs 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.basic4ppc.com/forum/basic4android-getting-started-tutorials/8385-variables-objects-basic4android.html):
    Code:
    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, 10dip10dip + 60dip * i, 200dip50dip)
        
    Next
    End Sub

    Sub Btn_Click
        
    Dim b As Button
        b = 
    Sender
        b.Color = 
    Colors.RGB(Rnd(0255), Rnd(0255), Rnd(0255))
    End Sub
    You can use Sender for many things.
     
  7. JMB

    JMB Active Member Licensed 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:
    Code:
    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:
    Code:
    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"
    Code:
    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:
    Code:
    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: May 15, 2011
  8. wheretheidivides

    wheretheidivides Active Member Licensed 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.
     
  9. Erel

    Erel Administrator Staff Member Licensed User

  10. Erel

    Erel Administrator Staff Member Licensed 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.
    Code:
    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':
    Code:
    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:
    Code:
    Activity.Color = 0xFFFF0000 'Red
    'Or:
    Activity.Color = 0xFF800080 'Purple
     
  11. gobblegob

    gobblegob Member Licensed User

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

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

    gobblegob Member Licensed User

    How to open a webpage with WebView.

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

    Code:
    Button1_Click
          
    Dim UserURL As String
          UserURL = 
    "http://www.google.com.au/"
                    WebView1.LoadUrl(UserURL)
             
    End Sub
    Hope this is helpful
     
  13. gobblegob

    gobblegob Member Licensed User

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

    Code:
    File.WriteString(File.DirDefaultExternal, "mytextfile.txt""text to write")
     
    Devan likes this.
  14. prokli

    prokli Active Member Licensed User


    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
     
  15. Harris

    Harris Well-Known Member Licensed 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:
    Code:
    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
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    "The application ... has stopped unexpectedly. Please try again." Some errors are not caught by Basic4android and then you see this message. To find the cause of the error you should check the unfiltered logs in the Logs tab (right pane). The filtered logs will usually not show any message about this error.
     
  17. Pfriemler

    Pfriemler Member Licensed 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)
    Code:
    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: May 19, 2011
    KMatle likes this.
  18. derez

    derez Expert Licensed User

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

    Pfriemler Member Licensed User

    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...
     
  20. agraham

    agraham Expert Licensed User

    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.
     
Thread Status:
Not open for further replies.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice