B4J Code Snippet [BANano]: Sharing the goodness

Ola

Thought I should create my own easy reference list of stuff I've posted here about BANano.

Tutorials
BANano for Dummies by Example
BANanoJSONQuery to the rescue: The case of the survey app.
Client Side Excel Report Generation [BANanoOXML]
Exploring BANanoEvents [BANano]
Sending Contact Us Form contents to an email with inline PHP [BANano]
Understanding CRUD logic with ExecuteCallBack [BANanoSQL]
Sharing the goodness [BANano]


Libraries
An Object Oriented UX library for BANano [BANanoWebix]
Got it! - Easy Hints [BANano]
A treeview you might use [BANano]
ChartJS charts with 1 line of code using UOECharts [BANano]
Implementing Collaboration with TogetherJS [BANano]
Implementing LiveHelp for your WebApp [ABMaterial]
Create your UX with MaterializaCSS using UOEBANano
UOEGrid: An interesting grid that you might like [BANano]
UOEGridTable Conditional Value Display Formatting [BANano]
UOEGridTable IconRenderer [BANano]
UOEGrid Column Renderer - Let's display images etc [BANano]
Creating Connected Grid Tables with UOEGridTable [BANano]
Creating Master Details Grid with UOEGridTable [BANano]


BackEnd

A BANanoSQL helper class for CRUD functionality [BANanoSQLUtils]
An inline PHP class for your MySQLI CRUD functionality [BANanoMySQL]
BANanoSQL CRUD-ing around with BANanoSQLUtils [BANano]
Exploring Using PHP & SQLite for your WebApp [BANano]
MySQL CRUD with PHP - Part 1 [BANano]
MySQL CRUD with PHP - Part 2 [BANano]
MySQL CRUD with PHP - Part 3.1 [A look an inline PHP] [BANano]
PDO CRUD Class for MSSQL [BANanoMSSQL]
SQLiteDB PHP CRUD Class for BANano [BANanoSQLite]

Experiments

A Material Design Lite framework for Website / WebApp Creation [BANanoReactMDL]
Beginning 3D with Three.JS [BANano3D]
Beginning HTML5 games with CreateJS [BANanoCreateJS]
Building WebApps/Websites with VueJS [BANanoVue]
15 Mockup Elements for your Prototypes [BANAnoWired]
Create reactive, state based components & UI [BANanoReef]
Creating a CRUD app with LocalStorage Backend [BANano]
Creating a hotel reservation app with BANanoJQM
Creating the PhotoNinja Website with UOE [Websites]
CRUD with grid & modal using UOENow [BANanoSQL]
Distributing and accessing an existing SQLite Databases - Part 1 [BANano]
A tabbed dialog to Login, Register, Forgot Password & Reset Password [BANano]
Let's please build a Community Project [BANanoReact]
Executing code without using BANano.Eval [BANano]


Questions
Question:
[SOLVED] Extending Event Driven BANanoSQL with own CallBacks?
Question: [SOLVED] How to maintain element events?
Question: [SOLVED] How to set BANanoEvent Bubbling Off?
Question: [SOLVED] BANanoMaterial Error Fix
Question: [SOLVED] How can I run a JavaScript Method and wait for it to finish?
Question: [SOLVED] Returning all list items in For Each
Question: [SOLVED] How does one use Header.AddMeta?
Question: [SOLVED] How to turn minify off/on
Question: [SOLVED] Empty string passed to getElementID('')
Question: [SOLVED] How to find element existence
Question: [SOLVED] How to CallSub inside #If JavaScript
Question: [SOLVED] Library Compilation FileNotFound Exception
Question: [SOLVED] Map.Initialize inclusion of map keys
Question: [SOLVED] How to transvese elements by name and return attributes
Question: [SOLVED] How to call different subs for different elements
Question: [SOLVED] RangeError: Maximum Stacktrace exceeded
Question: [SOLVED] How do I refresh a page
Question: [SOLVED] FloatingActionButton iif method not defined
Question: [SOLVED] Enumeration Initialization Assignments
Question: [SOLVED] Else If Transpiling Error
Question: [SOLVED] Map Object Enhancements
Question: [SOLVED] Support for String()
Question: [SOLVED] Using / Converting Own B4J Classes
Question: [SOLVED] Ajax Calls: How to convert B4J Http Calls

To relook at these *unresolved

Question:
How to embed & read a json file / rather use BANanoSQL to load it?
Question: How can I upload a file using Php?
Question: CRUD bug using wait
Question: Using MySQL / MSSQL with PHP
Question: How to add dynamic css / injectcss to my app
Question: How to AddJavascriptFile and AddCSSFile on demand

Now for some code snippets...

Removing Attributes

One of the elusive attributes is the 'disabled' attributes for elements. Apparently whether you set this to true/false to enable your element, the status quo stays the same. It seems the only way to toggle this is to remove it to enable your element.

The code snippet here is to remove attributes from elements.

B4X:
'remove an attribute
Sub removeAttr(elID As String, attrName As String)
    elID = elID.tolowercase
    Dim jQ As BANanoObject
    jQ.Initialize("$")
    jQ.Selector($"#${elID}"$).RunMethod("removeAttr", Array(attrName))
End Sub

#Tested

Update: 30 Jan 2019

A new method to remove attribute has been added as BANano.BANanoElement.RemoveAttr
 
Last edited:

Mashiane

Expert
Licensed User
For Loops

The For Each Loop (the variable type on the loop should be defined)

B4X:
write("For Each Loop<br /> ")
    Dim appNames() As String = Array("b4a", "b4i", "b4j", "b4r")
    For Each appName As String In appNames
        write(appName)
        write("<br />")
    Next
    write ("Exiting from the loop!")

Output

1600799707737.png


The Counter Loop

B4X:
write("Counter For Loop<br /> ")
    '
    Dim x As Int = 10
    Dim y As Int
    For y = 1 To x
        write($"y: ${y}"$)
        write("<br />")
   Next
    write ("Exiting counter loop!")

Output

1600799831333.png


The Step Down Loop

B4X:
Dim x As Int = 10
    Dim y As Int
    For y = 10 To 1 Step -1
        write($"y: ${y}"$)
        write("<br />")
    Next
    write ("Exiting step counter loop!")

1600799906031.png
 

Mashiane

Expert
Licensed User
Exiting & Skipping Loops

This is based on a condition

1. Here we exit as soon as the counter is 5

B4X:
write("Starting Do Loop ")
        
    Do Until (count = 10)
        write($"Current Count : ${count}<br />"$)
        count = count + 1
        '*****
        If count = 5 Then Exit
    Loop
   
    write("Loop stopped!")

Output

1600800283080.png


2. Here we skip and process the next loop line as soon as the item is 6

B4X:
Dim b As Int = 0
    For b = 1 To 10
        If b = 6 Then
            Continue
        End If
        document.write($"Item: ${b}</br>"$)   
    Next

output

1600800757488.png
 
Last edited:

Mashiane

Expert
Licensed User
A helper class to add a BANanoElement in any parent element.

B4X:
Sub AddElement(parentID As String, tag As String, id As String) As BANanoElement
    Dim el As BANanoElement = BANano.GetElement($"#${parentID}"$).Append($"<${tag} id="${id}"></${tag}>"$).Get($"#${id}"$)
    Return el
End Sub

Usage

B4X:
AddElement("body", "h1", "myh1").SetText("h1. Neumorphism UI heading")

Meaning:

Find the #body element, append to it a h1 element, set the id of the newly created h1 element to myh1, then set the text to "h1. Neomorphism UI heading


1601822944919.png
 

Mashiane

Expert
Licensed User
RunRecursive

B4X:
'run a recursive method
Sub RunRecursive(data As Map, path As String) As Object
    Dim prevObj As BANanoObject = data
    Dim items As List = BANano.Split(".", path)
    Dim iTot As Int = items.Size
    Dim iCnt As Int
    '
    Dim strprev As String = ""
    Dim prtObj As BANanoObject
    Dim litem As String = items.Get(iTot - 1)
    '
    For iCnt = 1 To iTot - 1
        'get the previos path
        strprev = items.Get(iCnt - 1)
        'the parent object
        prtObj = prevObj.GetField(strprev)
        'this does not exist, return
        If BANano.IsUndefined(prtObj) Then
            Return Null
        Else
            prevObj = prtObj
        End If
    Next
    Dim res As Object = prevObj.RunMethod(litem, Null).Result
    If BANano.IsUndefined(res) Then
        res = Null
    End If
    Return res
End Sub

Example code.. this executes a .RunMethod on the last path element delimited by .

Example Code

B4X:
Dim lat As Double = BANanoShared.RunRecursive(place, "geometry.location.lat")
    Dim lng As Double = BANanoShared.RunRecursive(place, "geometry.location.lng")

Ta!
 

Mashiane

Expert
Licensed User
B4X:
#if javascript
function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
#End If

'convert a dataURI to blob for form data
Sub dataURItoBlob(sDataURI As String) As BANanoObject
    Dim out As BANanoObject = BANano.RunJavascriptMethod("dataURItoBlob", Array(sDataURI))
    Return out
End Sub
 

Mashiane

Expert
Licensed User
Hex to RGB and back

B4X:
#if javascript
function rgbToHex(r, g, b) {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if(result){
      var r= parseInt(result[1], 16);
      var g= parseInt(result[2], 16);
      var b= parseInt(result[3], 16);
      return r+","+g+","+b;//return 23,14,45 -> reformat if needed 
  } 
  return null;
}
#End If

'convert RGB to HEX
Sub RGBToHex(r As Int, g As Int, b As String) As String
    Dim sout As String = BANano.RunJavascriptMethod("rgbToHex", Array(r, g, b))
    Return sout    
End Sub

'convert HEX to RGB
Sub HexToRGB(hexValue As String) As String
    Dim sout As String = BANano.RunJavascriptMethod("hexToRgb", Array(hexValue))
    Return sout    
End Sub
 
Top