### Basic4Android Directory Operations and Permissions Source: https://context7.com/aladkoi/basic4android/llms.txt Shows how to access different directories like internal, assets, external storage (requires permissions), and app-specific directories. Includes runtime permission checks for external storage on B4A and examples for B4J. ```basic 'Working with different directories Sub ExampleDirectories 'Internal storage (private to app) Log("Internal Dir: " & File.DirInternal) 'Assets folder (read-only) Log("Assets Dir: " & File.DirAssets) #If B4A 'External storage (SD card) Dim rp As RuntimePermissions rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE) Wait For Activity_PermissionResult (Permission As String, Result As Boolean) If Result Then Log("External Dir: " & File.DirRootExternal) End If #End If #If B4J 'Desktop directories Log("App Dir: " & File.DirApp) Log("Data Dir: " & File.DirData("MyApp")) #End If End Sub ``` -------------------------------- ### Programmatic UI Creation with XUI Views in B4X Source: https://context7.com/aladkoi/basic4android/llms.txt This code demonstrates how to programmatically create and configure various UI components like Labels, Panels, Buttons, ImageViews, and ScrollViews using the XUI library in B4X. It covers setting properties, adding views to the layout, handling events, and includes examples of animations and platform-specific conditional layouts. Dependencies include the XUI library and File I/O for loading bitmaps. ```basic Sub B4XPage_Created (Root1 As B4XView) Root = Root1 'Create Label Private lblTitle As B4XView lblTitle = xui.CreateLabel("") lblTitle.Text = "Hello World" lblTitle.TextColor = xui.Color_Blue lblTitle.Font = xui.CreateDefaultBoldFont(24) lblTitle.SetTextAlignment("CENTER", "CENTER") Root.AddView(lblTitle, 10dip, 10dip, 200dip, 50dip) 'Create Panel with color and border Private pnlMain As B4XView pnlMain = xui.CreatePanel("") pnlMain.SetColorAndBorder(xui.Color_White, 2dip, xui.Color_Blue, 10dip) Root.AddView(pnlMain, 10dip, 70dip, Root.Width - 20dip, 200dip) 'Create Button Private btnAction As B4XView btnAction = xui.CreateButton("") btnAction.Text = "Click Me" btnAction.SetColorAndBorder(xui.Color_RGB(50, 150, 250), 1dip, xui.Color_Black, 5dip) pnlMain.AddView(btnAction, 20dip, 20dip, 150dip, 50dip) 'Create ImageView Private imgLogo As B4XView imgLogo = xui.CreateImageView("") imgLogo.SetBitmap(xui.LoadBitmapResize(File.DirAssets, "logo.png", 100dip, 100dip, True)) pnlMain.AddView(imgLogo, 20dip, 80dip, 100dip, 100dip) 'Create ProgressBar Private pgProgress As B4XView pgProgress = xui.CreateProgressBar("") pgProgress.SetProgress(75) Root.AddView(pgProgress, 10dip, 280dip, Root.Width - 20dip, 30dip) 'Create ScrollView with dynamic content Private svContent As B4XView svContent = xui.CreateScrollView("") Root.AddView(svContent, 10dip, 320dip, Root.Width - 20dip, 300dip) 'Add multiple items to ScrollView Private pnlScroll As B4XView = xui.CreatePanel("") svContent.AddView(pnlScroll, 0, 0, svContent.Width, 1000dip) For i = 0 To 19 Private pnlItem As B4XView = xui.CreatePanel("") pnlItem.Color = IIF(i Mod 2 = 0, xui.Color_LightGray, xui.Color_White) pnlScroll.AddView(pnlItem, 0, i * 50dip, pnlScroll.Width, 49dip) Private lblItem As B4XView = xui.CreateLabel("") lblItem.Text = "Item " & (i + 1) lblItem.SetTextAlignment("CENTER", "CENTER") pnlItem.AddView(lblItem, 0, 0, pnlItem.Width, pnlItem.Height) Next 'Set event handler btnAction.SetOnClickListener(Me, "btnAction_Click") End Sub Private Sub btnAction_Click xui.MsgboxAsync("Button was clicked!", "Info") End Sub 'Animation example Private Sub AnimateViews lblTitle.SetLayoutAnimated(500, lblTitle.Left, 100dip, lblTitle.Width, lblTitle.Height) pnlMain.SetColorAnimated(1000, xui.Color_RGB(200, 200, 255), xui.Color_White) End Sub 'Conditional layout for different platforms Private Sub SetupPlatformSpecificUI #If B4A 'Android specific Root.Color = xui.Color_RGB(240, 240, 240) #Else If B4i 'iOS specific Root.Color = xui.Color_White #Else If B4J 'Desktop specific Root.Color = xui.Color_LightGray #End If End Sub ``` -------------------------------- ### B4X Class Module: Object-Oriented Programming Example Source: https://context7.com/aladkoi/basic4android/llms.txt Demonstrates creating a reusable class module in B4X for object-oriented programming. It includes initialization, properties (FirstName, LastName, BirthDate), and methods (GetName, GetCurrentAge, GetAgeAt). Usage in a main module is also shown. ```basic 'Class Person module Sub Class_Globals Private FirstName, LastName As String Private BirthDate As Long End Sub Sub Initialize (aFirstName As String, aLastName As String, aBirthDate As Long) FirstName = aFirstName LastName = aLastName BirthDate = aBirthDate End Sub Public Sub GetName As String Return FirstName & " " & LastName End Sub Public Sub GetCurrentAge As Int Return GetAgeAt(DateTime.Now) End Sub Public Sub GetAgeAt(Date As Long) As Int Private diff As Long diff = Date - BirthDate Return Floor(diff / DateTime.TicksPerDay / 365) End Sub 'Usage in Main Module Private p As Person p.Initialize("John", "Doe", DateTime.DateParse("05/12/1970")) Log(p.GetName) 'Output: John Doe Log(p.GetCurrentAge) 'Output: 54 (as of 2025) ``` -------------------------------- ### Basic4android SQLite Database Operations with DBUtils Source: https://context7.com/aladkoi/basic4android/llms.txt This snippet demonstrates comprehensive SQLite database management using DBUtils in Basic4android. It covers initializing the database, creating tables with specified columns and types, inserting multiple records from a list of maps, querying data with filtering and ordering, and displaying results as text logs or an HTML table in a WebView. It also includes examples for updating records based on specific criteria and deleting records. The snippet concludes with a practical demonstration of using transactions to ensure atomicity for multiple database insert operations. ```Basic4android Public SQL1 As SQL Public DBFileName = "persons.db" As String Public DBFileDir Public DBTableName = "persons" As String 'Initialize Database #If B4J DBFileDir = DBUtils.CopyDBFromAssets(DBFileName, "MyApp") SQL1.InitializeSQLite(DBFileDir, DBFileName, True) #Else DBFileDir = DBUtils.CopyDBFromAssets(DBFileName) SQL1.Initialize(DBFileDir, DBFileName, True) #End If 'Create Table Dim m As Map m.Initialize m.Put("FirstName", DBUtils.DB_TEXT) m.Put("LastName", DBUtils.DB_TEXT) m.Put("Address", DBUtils.DB_TEXT) m.Put("City", DBUtils.DB_TEXT) m.Put("Salary", DBUtils.DB_REAL) m.Put("Active", DBUtils.DB_INTEGER) DBUtils.CreateTable(SQL1, "persons", m, "PersonID") 'Insert Data Private lstAdd As List Private mapRow As Map lstAdd.Initialize mapRow.Initialize mapRow.Put("FirstName", "John") mapRow.Put("LastName", "Doe") mapRow.Put("Address", "123 Main St") mapRow.Put("City", "Springfield") mapRow.Put("Salary", 75000.50) mapRow.Put("Active", 1) lstAdd.Add(mapRow) mapRow.Initialize mapRow.Put("FirstName", "Jane") mapRow.Put("LastName", "Smith") mapRow.Put("Address", "456 Oak Ave") mapRow.Put("City", "Boston") mapRow.Put("Salary", 82000.00) mapRow.Put("Active", 1) lstAdd.Add(mapRow) DBUtils.InsertMaps(SQL1, "persons", lstAdd) 'Query Data Private Query As String Query = "SELECT FirstName, LastName, Address, City, Salary FROM persons WHERE Active = 1 ORDER BY LastName" Dim lstTable As List = DBUtils.ExecuteMemoryTable(SQL1, Query, Null, 0) 'Process results For i = 0 To lstTable.Size - 1 Dim rowValues() As String = lstTable.Get(i) Log("Name: " & rowValues(0) & " " & rowValues(1)) Log("City: " & rowValues(3) & ", Salary: " & rowValues(4)) Next 'Display in WebView as HTML table WebView1.LoadHtml(DBUtils.ExecuteHtml(SQL1, Query, Null, 0, True)) 'Update Record Private mapUpdate, mapWhere As Map mapUpdate.Initialize mapUpdate.Put("FirstName", "Janet") mapUpdate.Put("City", "Cambridge") mapUpdate.Put("Salary", 85000.00) mapWhere.Initialize mapWhere.Put("LastName", "Smith") DBUtils.UpdateRecord2(SQL1, "persons", mapUpdate, mapWhere) 'Delete Record Private mapWhere As Map mapWhere.Initialize mapWhere.Put("LastName", "Doe") DBUtils.DeleteRecord(SQL1, "persons", mapWhere) 'Using Transactions for Multiple Operations SQL1.BeginTransaction Try For i = 0 To 1000 mapRow.Initialize mapRow.Put("FirstName", "User" & i) mapRow.Put("LastName", "Test" & i) mapRow.Put("City", "TestCity") lstAdd.Initialize lstAdd.Add(mapRow) DBUtils.InsertMaps(SQL1, "persons", lstAdd) Next SQL1.TransactionSuccessful Catch Log("Database error: " & LastException) End Try SQL1.EndTransaction ``` -------------------------------- ### B4X Custom UI with XUI: Cross-Platform Button Example Source: https://context7.com/aladkoi/basic4android/llms.txt Illustrates creating a custom, cross-platform UI component (xCustomButton) using B4X and XUI. It supports designer properties, touch events, and custom methods like setText. Usage in a main module with event handling is provided. ```basic 'xCustomButton Class #Event: Click #Event: LongClick #Event: CheckedChange(Checked As Boolean) #DesignerProperty: Key: Text, DisplayName: Text, FieldType: String, DefaultValue: Button #DesignerProperty: Key: TextColor, DisplayName: Text Color, FieldType: Color, DefaultValue: 0xFF000000 Sub Class_Globals Private xui As XUI Private mEventName As String Private mCallBack As Object Private mBase As B4XView Public Tag As Object Private mText, mIcon As String Private mTextColor, mPressedColor As Int End Sub Public Sub Initialize (Callback As Object, EventName As String) mEventName = EventName mCallBack = Callback mIcon = Chr(0xE859) mText = "Test" mTextColor = xui.Color_Black mPressedColor = xui.Color_LightGray End Sub Public Sub DesignerCreateView (Base As Object, Lbl As Label, Props As Map) mBase = Base mBase.Tag = Me mText = Props.Get("Text") mTextColor = xui.PaintOrColorToColor(Lbl.TextColor) InitClass End Sub Private Sub InitClass mBase.SetColorAndBorder(xui.Color_White, 1dip, xui.Color_Black, 5dip) End Sub Private Sub mBase_Touch (Action As Int, X As Float, Y As Float) Select Action Case mBase.TOUCH_ACTION_DOWN mBase.Color = mPressedColor Case mBase.TOUCH_ACTION_UP mBase.Color = xui.Color_White If xui.SubExists(mCallBack, mEventName & "_Click", 0) Then CallSubDelayed(mCallBack, mEventName & "_Click") End If End Select End Sub Public Sub setText(Text As String) mText = Text DrawButton End Sub Public Sub getText As String Return mText End Sub 'Usage in Main Module Private btnCustom As xCustomButton btnCustom.Initialize(Me, "btnCustom") btnCustom.AddToParent(Root, 10dip, 10dip, 200dip, 50dip) btnCustom.Text = "Click Me" Private Sub btnCustom_Click Log("Button clicked!") xui.MsgboxAsync("Button was clicked", "Info") End Sub ``` -------------------------------- ### Make HTTP GET Request and Parse JSON Response (Basic4Android) Source: https://context7.com/aladkoi/basic4android/llms.txt Downloads data from a specified URL, parses the JSON response, and extracts relevant information like temperature, humidity, and condition. It handles success and error cases, and updates UI elements. Dependencies include HttpJob and JSONParser. ```basic Sub GetWeatherData(City As String) Dim job As HttpJob job.Initialize("WeatherJob", Me) job.Download("https://api.example.com/weather?city=" & City & "&apikey=YOUR_API_KEY") Wait For (job) JobDone(job As HttpJob) If job.Success Then 'Parse JSON response Dim json As JSONParser json.Initialize(job.GetString) Dim root As Map = json.NextObject Dim temperature As Double = root.Get("temperature") Dim humidity As Int = root.Get("humidity") Dim condition As String = root.Get("condition") Log("Temperature: " & temperature & "°C") Log("Humidity: " & humidity & "%") Log("Condition: " & condition) 'Update UI lblTemperature.Text = temperature & "°C" lblCondition.Text = condition Else Log("Error: " & job.ErrorMessage) xui.MsgboxAsync("Failed to load weather data: " & job.ErrorMessage, "Error") End If job.Release End Sub ``` -------------------------------- ### Basic4Android Get File Size Source: https://context7.com/aladkoi/basic4android/llms.txt A simple function to retrieve the size of a specified file in bytes. It takes the directory and file name as input and returns the file size as a Long. ```basic 'Check file size Sub GetFileSize(Dir As String, FileName As String) As Long Return File.Size(Dir, FileName) End Sub ``` -------------------------------- ### B4XPages Framework: Application Initialization and Page Management Source: https://context7.com/aladkoi/basic4android/llms.txt Demonstrates the application start-up logic for the B4XPages framework. It includes initializing the framework, adding pages to the navigation stack, and showing the initial page. ```b4x 'B4XPages.AddPage and Navigation Private Sub Application_Start B4XPages.Initialize B4XPages.AddPage("MainPage", MainPage) B4XPages.AddPage("SecondPage", SecondPage) B4XPages.AddPage("SettingsPage", SettingsPage) B4XPages.ShowPage("MainPage") End Sub ``` -------------------------------- ### B4XPages Framework: Main Page Implementation Source: https://context7.com/aladkoi/basic4android/llms.txt Defines the B4XMainPage, including its global variables, initialization, creation, appearance, disappearance, resizing logic for layout adjustments, and click event handlers for navigation to other pages. It also demonstrates how to share data between pages. ```b4x 'B4XMainPage - Main page of the application Sub Class_Globals Private Root As B4XView Private xui As XUI Private btnNext As B4XView Private lblTitle As B4XView Public SharedData As String End Sub Public Sub Initialize SharedData = "Initial Value" End Sub Private Sub B4XPage_Created (Root1 As B4XView) Root = Root1 Root.LoadLayout("MainPage") B4XPages.SetTitle(Me, "Main Page") End Sub Private Sub B4XPage_Appear Log("Main page is now visible") lblTitle.Text = "Welcome to " & B4XPages.GetTitle(Me) End Sub Private Sub B4XPage_Disappear Log("Main page is now hidden") End Sub Private Sub B4XPage_Resize (Width As Int, Height As Int) 'Handle orientation changes and resizing If Width > Height Then 'Landscape layout adjustments btnNext.SetLayoutAnimated(300, 50%x - 100dip, 80%y, 200dip, 50dip) Else 'Portrait layout adjustments btnNext.SetLayoutAnimated(300, 50%x - 100dip, 50%y, 200dip, 50dip) End If End Sub Private Sub btnNext_Click 'Navigate to another page B4XPages.ShowPage("SecondPage") End Sub Private Sub btnSettings_Click 'Show page and pass data Dim sp As Object = B4XPages.GetPage("SettingsPage") B4XPages.ShowPage("SettingsPage") End Sub ``` -------------------------------- ### B4XPages Framework: Second Page Implementation Source: https://context7.com/aladkoi/basic4android/llms.txt Implements the B4XSecondPage, handling its creation, appearance, and the back navigation. It shows how to access data passed from the main page and close the current page. ```b4x 'B4XSecondPage - Second page Sub Class_Globals Private Root As B4XView Private xui As XUI Private btnBack As B4XView End Sub Public Sub Initialize End Sub Private Sub B4XPage_Created (Root1 As B4XView) Root = Root1 Root.LoadLayout("SecondPage") B4XPages.SetTitle(Me, "Second Page") End Sub Private Sub B4XPage_Appear 'Access data from main page Dim mp As B4XMainPage = B4XPages.GetPage("MainPage") Log("Shared data: " & mp.SharedData) End Sub Private Sub btnBack_Click 'Close current page and return to previous B4XPages.ClosePage(Me) End Sub ``` -------------------------------- ### Responsive Layouts with Designer Scripts in B4X Source: https://context7.com/aladkoi/basic4android/llms.txt This script illustrates how to create responsive user interfaces that adapt to various screen sizes and orientations using B4X Designer Scripts. It demonstrates positioning and resizing UI elements based on screen dimensions, including variant-specific adjustments for landscape and tablet layouts. The script also includes an AutoScaleAll function for automatic scaling adjustments. ```basic 'Layout file: MainPage.bal 'General script (applies to all variants) pnlToolBox.HorizontalCenter = 50%x ListView1.SetLeftAndRight(10dip, 10dip) ListView1.SetTopAndBottom(10dip, pnlToolBox.Top - 10dip) 'Button panel positioning pnlButtons.HorizontalCenter = 50%x pnlButtons.Top = 10dip 'Make list view fill remaining space ListView1.SetTopAndBottom(pnlButtons.Bottom + 10dip, pnlStatus.Top - 10dip) 'Status bar at bottom pnlStatus.SetLeftAndRight(0, 0) pnlStatus.Top = 100%y - pnlStatus.Height 'Variant-specific script for landscape '320x480,scale=1 If Root.Width > Root.Height Then 'Landscape orientation pnlToolBox.Left = Root.Width - pnlToolBox.Width - 10dip pnlToolBox.SetTopAndBottom(10dip, 10dip) ListView1.SetLeftAndRight(10dip, pnlToolBox.Left - 10dip) ListView1.SetTopAndBottom(10dip, pnlStatus.Top - 10dip) Else 'Portrait orientation pnlToolBox.HorizontalCenter = 50%x pnlToolBox.Top = Root.Height - pnlToolBox.Height - 10dip - pnlStatus.Height ListView1.SetTopAndBottom(10dip, pnlToolBox.Top - 10dip) End If 'Tablet variant (600x800,scale=1.5) If Root.Width >= 600dip Then 'Use two-column layout on tablets ListView1.Width = 50%x - 15dip pnlDetails.Left = ListView1.Right + 10dip pnlDetails.Width = 50%x - 15dip pnlDetails.SetTopAndBottom(10dip, pnlStatus.Top - 10dip) pnlDetails.Visible = True Else 'Single column on phones ListView1.SetLeftAndRight(10dip, 10dip) pnlDetails.Visible = False End If 'AutoScale adjustments AutoScaleAll ``` -------------------------------- ### Download and Display Image from URL (Basic4Android) Source: https://context7.com/aladkoi/basic4android/llms.txt Downloads an image from a given URL, saves it to internal storage, and then loads and displays it in an ImageView. It utilizes HttpJob for downloading and File I/O operations for saving and loading the image. Dependencies include HttpJob, File, and Bitmap. ```basic Sub DownloadImage(ImageUrl As String, FileName As String) Dim job As HttpJob job.Initialize("ImageDownload", Me) job.Download(ImageUrl) Wait For (job) JobDone(job As HttpJob) If job.Success Then 'Save image to file Dim out As OutputStream = File.OpenOutput(File.DirInternal, FileName, False) File.Copy2(job.GetInputStream, out) out.Close 'Load and display image Dim bmp As Bitmap = LoadBitmap(File.DirInternal, FileName) imgView.Bitmap = bmp Log("Image downloaded: " & FileName) Else Log("Error downloading image: " & job.ErrorMessage) End If job.Release End Sub ``` -------------------------------- ### Make HTTP POST Request with JSON Data (Basic4Android) Source: https://context7.com/aladkoi/basic4android/llms.txt Sends user data (username, email) to a REST API using an HTTP POST request with a JSON payload. It initializes HttpJob, prepares the data using JSONGenerator, sets the content type, and handles the server response. Dependencies include HttpJob, JSONGenerator, and DateTime. ```basic Sub PostUserData(Username As String, Email As String) Dim job As HttpJob job.Initialize("PostJob", Me) 'Create JSON data Dim mapData As Map mapData.Initialize mapData.Put("username", Username) mapData.Put("email", Email) mapData.Put("timestamp", DateTime.Now) Dim json As JSONGenerator json.Initialize(mapData) 'POST request with JSON job.PostString("https://api.example.com/users", json.ToString) job.GetRequest.SetContentType("application/json") Wait For (job) JobDone(job As HttpJob) If job.Success Then Log("User created successfully") Log("Response: " & job.GetString) 'Parse response Dim jsonResponse As JSONParser jsonResponse.Initialize(job.GetString) Dim response As Map = jsonResponse.NextObject Dim userId As String = response.Get("id") Log("New user ID: " & userId) Else Log("Error: " & job.ErrorMessage) End If job.Release End Sub ``` -------------------------------- ### Basic4Android Main Module Using Custom Event Handler Source: https://context7.com/aladkoi/basic4android/llms.txt This code demonstrates the usage of the 'xLimitBar' custom view in a Basic4Android main module. It initializes the custom view, sets its properties, and defines event handlers for 'ValuesChanged', 'TouchDown', and 'TouchUp'. The event handlers update UI elements like labels and log messages to reflect user interactions with the custom control. Dependencies include B4XView and the 'xLimitBar' custom class. ```basic 'Main Module - Using Custom Events Private ltbPriceRange As xLimitBar Sub B4XPage_Created (Root1 As B4XView) Root = Root1 Root.LoadLayout("MainPage") 'Initialize with event name ltbPriceRange.Initialize(Me, "ltbPriceRange") ltbPriceRange.Min = 0 ltbPriceRange.Max = 1000 End Sub 'Event handlers in calling module Private Sub ltbPriceRange_ValuesChanged(LimitLeft As Int, LimitRight As Int) lblMinPrice.Text = "$" & LimitLeft lblMaxPrice.Text = "$" & LimitRight Log("Price range: $" & LimitLeft & " - $" & LimitRight) UpdateProductList(LimitLeft, LimitRight) End Sub Private Sub ltbPriceRange_TouchDown Log("User started adjusting price range") pnlHighlight.Visible = True End Sub Private Sub ltbPriceRange_TouchUp Log("User finished adjusting price range") pnlHighlight.Visible = False SaveUserPreferences End Sub ``` -------------------------------- ### Upload File using Multipart Form Data (Basic4Android) Source: https://context7.com/aladkoi/basic4android/llms.txt Uploads a local file to a server using an HTTP POST request with multipart form data. It prepares the file data, including its name, key, and content type, and sends it along with other form data. Dependencies include HttpJob and MultipartFileData. ```basic Sub UploadFile(FilePath As String, FileName As String) Dim job As HttpJob job.Initialize("UploadJob", Me) 'Upload file with multipart form data Dim fd As MultipartFileData fd.Initialize fd.Dir = File.DirInternal fd.FileName = FileName fd.KeyName = "file" fd.ContentType = "image/jpeg" job.PostMultipart("https://api.example.com/upload", CreateMap("description": "User upload"), Array(fd)) Wait For (job) JobDone(job As HttpJob) If job.Success Then Log("File uploaded successfully") Dim response As String = job.GetString Log("Server response: " & response) Else Log("Upload failed: " & job.ErrorMessage) End If job.Release End Sub ``` -------------------------------- ### Basic4Android File Read/Write Operations Source: https://context7.com/aladkoi/basic4android/llms.txt Demonstrates reading and writing text files, lists, and maps (as JSON) to the internal storage. It includes saving user preferences, settings, and user profile data, as well as loading this data back. ```basic 'File reading and writing Sub SaveUserData 'Write text file File.WriteString(File.DirInternal, "userdata.txt", "User preferences data") 'Write list to file Dim lstSettings As List lstSettings.Initialize lstSettings.Add("Theme=Dark") lstSettings.Add("Language=English") lstSettings.Add("AutoSave=True") File.WriteList(File.DirInternal, "settings.txt", lstSettings) 'Write map to JSON Dim mapUser As Map mapUser.Initialize mapUser.Put("username", "john.doe") mapUser.Put("email", "john@example.com") mapUser.Put("lastLogin", DateTime.Now) Dim json As JSONGenerator json.Initialize(mapUser) File.WriteString(File.DirInternal, "user.json", json.ToString) Log("Data saved successfully") End Sub Sub LoadUserData 'Read text file If File.Exists(File.DirInternal, "userdata.txt") Then Dim userData As String = File.ReadString(File.DirInternal, "userdata.txt") Log("User data: " & userData) End If 'Read list from file If File.Exists(File.DirInternal, "settings.txt") Then Dim lstSettings As List = File.ReadList(File.DirInternal, "settings.txt") For i = 0 To lstSettings.Size - 1 Log("Setting: " & lstSettings.Get(i)) Next End If 'Read JSON to map If File.Exists(File.DirInternal, "user.json") Then Dim jsonText As String = File.ReadString(File.DirInternal, "user.json") Dim json As JSONParser json.Initialize(jsonText) Dim mapUser As Map = json.NextObject Log("Username: " & mapUser.Get("username")) Log("Email: " & mapUser.Get("email")) End If End Sub ``` -------------------------------- ### Basic4Android Custom Event Handling in xLimitBar Class Source: https://context7.com/aladkoi/basic4android/llms.txt This code defines a custom view class 'xLimitBar' in Basic4Android. It implements custom event handling for 'ValuesChanged', 'TouchDown', and 'TouchUp'. The class manages touch events on a panel to allow users to adjust limit values, raising events to notify the calling module of changes and touch actions. Dependencies include B4XView and xui. ```basic 'xLimitBar Custom View Class #Event: ValuesChanged(LimitLeft As Int, LimitRight As Int) #Event: TouchDown #Event: TouchUp #RaisesSynchronousEvents: ValuesChanged, TouchDown, TouchUp Sub Class_Globals Private mCallback As Object Private mEventName As String Private mLimit(2) As Int Private ltbPanelFront As B4XView End Sub Public Sub Initialize(Callback As Object, EventName As String) mCallback = Callback mEventName = EventName mLimit(0) = 0 mLimit(1) = 100 End Sub Private Sub ltbPanelFront_Touch (Action As Int, X As Double, Y As Double) Private xx As Double xx = Max(x0, Min(x1, X)) Select Action Case ltbPanelFront.TOUCH_ACTION_DOWN 'Raise TouchDown event If xui.SubExists(mCallback, mEventName & "_TouchDown", 0) Then CallSub(mCallback, mEventName & "_TouchDown") End If 'Determine which cursor to move If xx < Abs(PositionPixels(0) + PositionPixels(1)) / 2 Then PosIndex = 0 Else PosIndex = 1 End If Case ltbPanelFront.TOUCH_ACTION_MOVE 'Update position and raise event PositionPixels(PosIndex) = xx mLimit(PosIndex) = (xx - x0) / Scale DrawCursors If xui.SubExists(mCallback, mEventName & "_ValuesChanged", 2) Then CallSub3(mCallback, mEventName & "_ValuesChanged", mLimit(0), mLimit(1)) End If Case ltbPanelFront.TOUCH_ACTION_UP 'Raise final ValuesChanged event If xui.SubExists(mCallback, mEventName & "_ValuesChanged", 2) Then CallSub3(mCallback, mEventName & "_ValuesChanged", mLimit(0), mLimit(1)) End If 'Raise TouchUp event If xui.SubExists(mCallback, mEventName & "_TouchUp", 0) Then CallSub(mCallback, mEventName & "_TouchUp") End If End Select End Sub 'Getters and Setters for properties Public Sub setMin(MinValue As Int) mLimit(0) = MinValue UpdateDisplay End Sub Public Sub getMin As Int Return mLimit(0) End Sub Public Sub setMax(MaxValue As Int) mLimit(1) = MaxValue UpdateDisplay End Sub Public Sub getMax As Int Return mLimit(1) End Sub ``` -------------------------------- ### Basic4Android Shape Classes for Polymorphism Source: https://context7.com/aladkoi/basic4android/llms.txt Defines abstract 'Shape' behaviors (Draw, GetArea, GetPerimeter) implemented by concrete 'Square', 'Circle', and 'Triangle' classes. Each class includes an Initialize method to set properties and add itself to a shared 'Shapes' list. Dependencies include Basic4Android's Canvas and List objects. ```Basic4Android 'Square Class Sub Class_Globals Private mx, my, mLength As Int Private mColor As Int End Sub Sub Initialize (Shapes As List, x As Int, y As Int, length As Int, Color As Int) mx = x my = y mLength = length mColor = Color Shapes.Add(Me) End Sub Sub Draw(c As Canvas) Private r As Rect r.Initialize(mx, my, mx + mLength, my + mLength) c.DrawRect(r, mColor, True, 1dip) End Sub Sub GetArea As Double Return mLength * mLength End Sub Sub GetPerimeter As Double Return 4 * mLength End Sub 'Circle Class Sub Class_Globals Private mx, my, mRadius As Int Private mColor As Int End Sub Sub Initialize (Shapes As List, x As Int, y As Int, radius As Int, Color As Int) mx = x my = y mRadius = radius mColor = Color Shapes.Add(Me) End Sub Sub Draw(cvs As Canvas) cvs.DrawCircle(mx, my, mRadius, mColor, True, 1dip) End Sub Sub GetArea As Double Return cPI * mRadius * mRadius End Sub Sub GetPerimeter As Double Return 2 * cPI * mRadius End Sub 'Triangle Class Sub Class_Globals Private mx1, my1, mx2, my2, mx3, my3 As Int Private mColor As Int End Sub Sub Initialize (Shapes As List, x1 As Int, y1 As Int, x2 As Int, y2 As Int, x3 As Int, y3 As Int, Color As Int) mx1 = x1 my1 = y1 mx2 = x2 my2 = y2 mx3 = x3 my3 = y3 mColor = Color Shapes.Add(Me) End Sub Sub Draw(c As Canvas) Private path As Path path.Initialize(mx1, my1) path.LineTo(mx2, my2) path.LineTo(mx3, my3) path.LineTo(mx1, my1) c.DrawPath(path, mColor, True, 1dip) End Sub Sub GetArea As Double Return Abs((mx1 * (my2 - my3) + mx2 * (my3 - my1) + mx3 * (my1 - my2)) / 2) End Sub ``` -------------------------------- ### Basic4Android Polymorphic Shape Drawing and Calculation Source: https://context7.com/aladkoi/basic4android/llms.txt This code snippet demonstrates polymorphism by creating instances of different shape classes (Square, Circle, Triangle) and storing them in a list. It then iterates through the list, dynamically calling the 'Draw', 'GetArea', and 'GetPerimeter' methods on each shape object using CallSub2 and CallSub, showcasing duck typing. ```Basic4Android 'Main Code - Using Polymorphism Private Shapes As List Private cvs As Canvas Shapes.Initialize 'Create different shapes Private Square1 As Square Private Circle1 As Circle Private Triangle1 As Triangle Square1.Initialize(Shapes, 10dip, 10dip, 50dip, Colors.Red) Circle1.Initialize(Shapes, 150dip, 100dip, 40dip, Colors.Blue) Triangle1.Initialize(Shapes, 250dip, 50dip, 300dip, 150dip, 200dip, 150dip, Colors.Green) 'Draw all shapes using polymorphism cvs.Initialize(Panel1) For i = 0 To Shapes.Size - 1 Dim shape As Object = Shapes.Get(i) CallSub2(shape, "Draw", cvs) 'Get area and perimeter Dim area As Double = CallSub(shape, "GetArea") Dim perimeter As Double = CallSub(shape, "GetPerimeter") Log("Shape " & i & ": Area=" & NumberFormat(area, 1, 2) & ", Perimeter=" & NumberFormat(perimeter, 1, 2)) Next Panel1.Invalidate ``` -------------------------------- ### Basic4Android File Copy Operation Source: https://context7.com/aladkoi/basic4android/llms.txt Provides a function to copy a file from the application's assets folder to its internal storage. Includes basic error handling using a Try-Catch block. ```basic 'Copy file from assets to internal storage Sub CopyAssetFile(FileName As String) As Boolean Try File.Copy(File.DirAssets, FileName, File.DirInternal, FileName) Return True Catch Log("Error copying file: " & LastException) Return False End Try End Sub ``` -------------------------------- ### Basic4Android File Deletion and Cleanup Source: https://context7.com/aladkoi/basic4android/llms.txt Implements a routine to delete old files from internal storage based on their last modified date. Files older than 7 days are removed to manage storage space. ```basic 'Delete old files Sub CleanupOldFiles Dim filesList As List = File.ListFiles(File.DirInternal) Dim now As Long = DateTime.Now Dim daysToKeep As Long = 7 * DateTime.TicksPerDay For i = 0 To filesList.Size - 1 Dim fileName As String = filesList.Get(i) Dim fileDate As Long = File.LastModified(File.DirInternal, fileName) If now - fileDate > daysToKeep Then File.Delete(File.DirInternal, fileName) Log("Deleted old file: " & fileName) End If Next End Sub ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.