image
SaveAs - Let the user select a target folder

2021-04-22 13:21:55 by Omar
Original Link Author Link
                                    Sub SaveAs (Source As InputStream, MimeType As String, Title As String) As ResumableSub
    Dim intent As Intent
    intent.Initialize("android.intent.action.CREATE_DOCUMENT", "")
    intent.AddCategory("android.intent.category.OPENABLE")
    intent.PutExtra("android.intent.extra.TITLE", Title)
    intent.SetType(MimeType)
    StartActivityForResult(intent)
    Wait For ion_Event (MethodName As String, Args() As Object)
    If -1 = Args(0) Then 'resultCode = RESULT_OK
        Dim result As Intent = Args(1)
        Dim jo As JavaObject = result
        Dim ctxt As JavaObject
        Dim out As OutputStream = ctxt.InitializeContext.RunMethodJO("getContentResolver", Null).RunMethod("openOutputStream", Array(jo.RunMethod("getData", Null)))
        File.Copy2(Source, out)
        out.Close
        Return True
    End If
    Return False
End Sub

Sub StartActivityForResult(i As Intent)
    Dim jo As JavaObject = GetBA
    ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
    jo.RunMethod("startActivityForResult", Array(ion, i))
End Sub

Sub GetBA As Object
    Dim jo As JavaObject = Me
    Return jo.RunMethod("getBA", Null)
End Sub


HOW TO USE (B4XPages)

Private Sub Button1_Click
    File.WriteString(File.DirInternal, "test.txt", "test") 'just for the example.
    Wait For (SaveAs(File.OpenInput(File.DirInternal, "test.txt"), "application/octet-stream", "test.txt")) Complete (Success As Boolean)
    Log("File saved successfully? " & Success)
End Sub

HOW TO USE (SIMPLE)

Sub GetBA As Object
   Dim jo As JavaObject
   Dim cls As String = Me
   cls = cls.SubString("class ".Length)
   jo.InitializeStatic(cls)
   Return jo.GetField("processBA")
End Sub

                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : ContentChooser, SAVE AS, user select target folder
image
Firestore API REST

2021-04-22 13:26:53 by Omar
Original Link Author Link
                                    ' READ DOCUMENT

Public Sub getDocument(Coleccion As String) As ResumableSub
   
    Dim link As String = $"https://firestore.googleapis.com/v1/projects/{projectId}/databases/(default)/documents/${Coleccion}"$

       
    Dim okHttp As HttpJob
    okHttp.Initialize("HTTP", Me)
   
    okHttp.Download(link & "info_chats")
    Wait For (okHttp) JobDone(j As HttpJob)
       
    If j.Success Then
       
        Log(j.GetString)
        Dim jsonString As JSONParser
        jsonString.Initialize(j.GetString)
        Dim map As Map = jsonString.NextObject

        Return map
       
    Else
        Log(j.ErrorMessage)
    End If

End Sub

Example:
Wait For (getDocument("server/names")) Complete(m As Map)

' VALUES:


Public Sub patchValues(Token As String, collection As String, Campos As Map) As ResumableSub
   
    Dim url As String = $"https://firestore.googleapis.com/v1/projects/{projectId}/databases/(default)/documents${collection}"$'?documentId=${Documento}"$
    Dim Json As JSONGenerator
    Json.Initialize(CreateMap("fields":Campos))
   
    Dim j As HttpJob : j.Initialize("",Me)
    Log(Json.ToString)
   
    j.PatchString(url,Json.ToString)
    j.GetRequest.SetHeader("Authorization","Bearer " & Token)
    j.GetRequest.SetContentType("application/json")
   
    Wait For (j) JobDone(j As HttpJob)
    Return GenerateResult(j)

End Sub

' Example:


Wait For (patchValues(UserTokenId, "info_chats/id_group_chat1", CreateMap("name" : CreateMap("stringValue": "Paolo")))) Complete(m As Map)


' Create document:



Public Sub createDocument(Token As String, collection As String, Documento As String, Campos As Map) As ResumableSub
   
    Dim url As String = $"https://firestore.googleapis.com/v1/projects/{projectId}/databases/(default)/documents/${collection}?documentId=${Documento}"$
    Dim json As JSONGenerator
    json.Initialize(CreateMap("fields":Campos))
   
    Dim j As HttpJob : j.Initialize("",Me)
    Log(json.ToString)
    j.PostString(url,json.ToString)
    j.GetRequest.SetHeader("Authorization","Bearer " & Token)
    j.GetRequest.SetContentType("application/json")
   
    Wait For (j) JobDone(j As HttpJob)
    Return GenerateResult(j)

End Sub

' Example:
Wait For (Firestore.createDocument(UserTokenId, "info_chats","Profile", CreateMap("name" : CreateMap("stringValue": "Paolo")))) Complete(m As Map)

' Deletedocument:


Public Sub deleteDocument(Token As String, collection As String) As ResumableSub
   
    Dim url As String = $"https://firestore.googleapis.com/v1/projects/{projectid}/databases/(default)/documents/${collection}"$'?documentId=${Documento}"$

    Dim j As HttpJob : j.Initialize("",Me)
    j.Delete(url)
    j.GetRequest.SetHeader("Authorization","Bearer " & Token)
   
    Wait For (j) JobDone(j As HttpJob)
    Return GenerateResult(j)

End Sub

'EXAMPLE:
Wait For (Firestore.deleteDocument(UserTokenId, "info_chats/Profile")) Complete(m As Map)

' SUJESTED USE OF CODE WITH MAP
Private Sub GenerateResult(j As HttpJob) As Map
    Dim response As String = ""
    If j.Success Then
        response = j.GetString
        Log(j.GetString)
    Else
        response = j.ErrorMessage
    End If
    
    Dim parser As JSONParser
    parser.Initialize(response)
    Dim tmp_result As Map = parser.NextObject
    tmp_result.Put("success",j.Success)
    
    j.Release
    Return tmp_result
End Sub








                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : Firestore API REST, firestore, api
image
B4XDialog - show with animation

2021-04-22 13:29:04 by Omar
Original Link Author Link
                                    

Sub AnimateDialog (dlg As B4XDialog, FromEdge As String)
    Dim base As B4XView = dlg.Base
    Dim top As Int = base.Top
    Dim left As Int = base.Left
    Select FromEdge.ToLowerCase
        Case "bottom"
            base.Top = base.Parent.Height
        Case "top"
            base.Top = -base.Height
        Case "left"
            base.Left = -base.Width
        Case "right"
            base.Left = base.Parent.Width
    End Select
    base.SetLayoutAnimated(300, left, top, base.Width, base.Height)
End Sub


' HOW TO USE:
Sub Globals
    Private dialog As B4XDialog
    Private xui As XUI
End Sub

Sub Activity_Create(FirstTime As Boolean)
    dialog.Initialize(Activity)
    dialog.Title = "test"
End Sub

Sub Activity_Click
    Dim rs As Object = dialog.Show("aaa", "Ok", "Not Ok", "")
    AnimateDialog(dialog, "right")
    Wait For (rs) Complete (Result As Int)
    If Result = xui.DialogResponse_Positive Then
        '...
    End If
End Sub

 
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : dialog, animation, dialog animation
image
Wait for - Example

2021-04-26 23:35:50 by Omar
Original Link Author Link
                                    Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
   Log(j.GetString)
End If
j.Release
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : WAIT FOR, download
image
Download quote from API

2021-04-26 23:42:57 by Omar
Original Link Author Link
                                    Sub DownloadQuote
   Dim j As HttpJob
   j.Initialize("", Me) 'name is empty as it is no longer needed
   j.Download("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand")
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
     'The result is a json string. We parse it and log the fields.
     Dim jp As JSONParser
     jp.Initialize(j.GetString)
     Dim quotes As List = jp.NextArray
     For Each quot As Map In quotes
       Log("Title: " & quot.Get("title"))
       Log("Content: " & quot.Get("content"))
     Next
   End If
   j.Release
End Sub
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : download quote, download, wait for
image
Download Multiple resources one after another

2021-04-27 12:46:18 by Omar
Original Link Author Link
                                    

Sub Activity_Create(FirstTime As Boolean)
   DownloadMany(Array("http://www.google.com", "http://duckduckgo.com", "http://bing.com"))
End Sub

Sub DownloadMany (links As List)
   For Each link As String In links
     Dim j As HttpJob
     j.Initialize("", Me) 'name is empty as it is no longer needed
     j.Download(link)
     Wait For (j) JobDone(j As HttpJob)
     If j.Success Then
       Log("Current link: " & link)
       Log(j.GetString)
     End If
     j.Release
   Next
End Sub


                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : wait for, donwload
image
Download Image an set on Imageview

2021-04-27 12:48:38 by Omar
Original Link Author Link
                                    

Sub DownloadImage(Link As String, iv As ImageView)
   Dim j As HttpJob
   j.Initialize("", Me)
   j.Download(Link)
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
     iv.Bitmap = j.GetBitmap
   End If
   j.Release
End Sub


                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : download image , imageview
image
Download an Image an save locally

2021-04-27 12:50:26 by Omar
Original Link Author Link
                                    Sub DownloadAndSaveFile (Link As String)
   Dim j As HttpJob
   j.Initialize("", Me)
   j.Download(Link)
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
       Dim out As OutputStream = File.OpenOutput(File.DirInternal, "filename.dat", False)
     File.Copy2(j.GetInputStream, out)
     out.Close ------ very important
   End If
   j.Release
End Sub
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : download image, save image locally
image
FTP Server implemented with Socket and AsyncStreams

files are included

2021-04-28 18:55:34 by Omar
Original Link Author Link
                                    server.Initialize(Main, "FTPServer")
server.SetPorts(51041, 51042, 51142)
server.AddUser("Test", "test") 'user name and password.
server.BaseDir = File.DirRootExternal
server.Start
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : ftp server
FTPServer_b4xsnippets.com.b4xlibB4A_FTPServer_b4xsnippets.com.zip
image
Confirm Dialog

The sample shows how to delete a file, previously shows a dialog with 3 options the "yes" return -1, the rest cancel the dialog

2022-02-10 03:05:05 by Omar
Original Link Author Link
                                    Private Sub swbtnDelete_Click
	Dim confirmDialog As B4XDialog
	confirmDialog.Initialize(Root)
	
	Wait For (confirmDialog.Show("Sure?", "YES", "NO", "CANCEL")) Complete (Result As Int)
	If Result = xui.DialogResponse_Positive Then
		Log(Result)
		File.Delete(xui.DefaultFolder & "privateCABINET" ,listofpics.Get(currentPreviewIndexfile))
		pnlPreview.Visible=False
	End If
	
End Sub
                                

Android - B4A iOS - B4i Desktop - B4J Multiplatform - B4X

TAGS : confirm dialog, confim, dialog
image
Make your app files accessible with Files app

Copy the code on the top of your main module

2022-02-16 18:32:52 by Omar
Original Link Author Link
                                    #PlistExtra: LSSupportsOpeningDocumentsInPlaceUIFileSharingEnabled
                                

iOS - B4i

TAGS : publish files, files,documents
image
Get iPhone Model

2022-02-16 18:35:49 by Omar
Original Link Author Link
                                    

Sub GetDeviceModelName As String
    Dim no As NativeObject = Me
    Return no.RunMethod("deviceName", Null).AsString
End Sub

#if OBJC
#import 
- (NSString*) deviceName
{
struct utsname systemInfo;

uname(&systemInfo);

NSString* code = [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];

static NSDictionary* deviceNamesByCode = nil;

if (!deviceNamesByCode) {

deviceNamesByCode = @{@"i386" :@"Simulator",
@"x86_64" :@"Simulator",
@"iPod1,1" :@"iPod Touch", // (Original)
@"iPod2,1" :@"iPod Touch", // (Second Generation)
@"iPod3,1" :@"iPod Touch", // (Third Generation)
@"iPod4,1" :@"iPod Touch", // (Fourth Generation)
@"iPod7,1" :@"iPod Touch", // (6th Generation)
@"iPhone1,1" :@"iPhone", // (Original)
@"iPhone1,2" :@"iPhone", // (3G)
@"iPhone2,1" :@"iPhone", // (3GS)
@"iPhone3,1" :@"iPhone 4", // (GSM)
@"iPhone3,3" :@"iPhone 4", // (CDMA/Verizon/Sprint)
@"iPhone4,1" :@"iPhone 4S", //
@"iPhone5,1" :@"iPhone 5", // (model A1428, AT&T/Canada)
@"iPhone5,2" :@"iPhone 5", // (model A1429, everything else)
@"iPhone5,3" :@"iPhone 5c", // (model A1456, A1532 | GSM)
@"iPhone5,4" :@"iPhone 5c", // (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" :@"iPhone 5s", // (model A1433, A1533 | GSM)
@"iPhone6,2" :@"iPhone 5s", // (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" :@"iPhone 6 Plus", //
@"iPhone7,2" :@"iPhone 6", //
@"iPhone8,1" :@"iPhone 6S", //
@"iPhone8,2" :@"iPhone 6S Plus", //
@"iPhone8,4" :@"iPhone SE", //
@"iPhone9,1" :@"iPhone 7 (CDMA)", //
@"iPhone9,3" :@"iPhone 7 (GSM)", //
@"iPhone9,2" :@"iPhone 7 Plus (CDMA)", //
@"iPhone9,4" :@"iPhone 7 Plus (GSM)", //
@"iPhone10,1" :@"iPhone 8 (CDMA)", //
@"iPhone10,4" :@"iPhone 8 (GSM)", //
@"iPhone10,2" :@"iPhone 8 Plus (CDMA)", //
@"iPhone10,5" :@"iPhone 8 Plus (GSM)", //
@"iPhone10,3" :@"iPhone X (CDMA)", //
@"iPhone10,6" :@"iPhone X (GSM)", //
@"iPhone11,2" :@"iPhone XS", //
@"iPhone11,4" :@"iPhone XS Max", //
@"iPhone11,6" :@"iPhone XS Max China", //
@"iPhone11,8" :@"iPhone XR", //
@"iPhone12,8" :@"iPhone SE (2nd generation)", //
@"iPhone13,1" :@"iPhone 12 mini", //
@"iPhone13,2" :@"iPhone 12", //
@"iPhone13,3" :@"iPhone 12 Pro", //
@"iPhone13,4" :@"iPhone 12 Pro Max", //

@"iPad1,1" :@"iPad", // (Original)
@"iPad2,1" :@"iPad 2 Wifi", // (model A1395)
@"iPad2,2" :@"iPad 2 GSM", // (model A1396)
@"iPad2,3" :@"iPad 2 3G", // (model A1397)
@"iPad2,4" :@"iPad 2 Wifi", //(model A1395)
@"iPad2,5" :@"iPad Mini Wifi ", // (model A1432)
@"iPad2,6" :@"iPad Mini Wifi + Cellular", // (model A1454)
@"iPad2,7" :@"iPad Mini Wifi + Cellular", // (model A1455)
@"iPad3,1" :@"iPad 3", // (3rd Generation)
@"iPad3,2" :@"iPad 3 Wifi + Cellular", // (model A1403)
@"iPad3,3" :@"iPad 3 Wifi + Cellular", // (model A1430)
@"iPad3,4" :@"iPad 4 Wifi ", // (model A1458)
@"iPad3,5" :@"iPad 4 Wifi + Cellular", // (model A1459)
@"iPad3,6" :@"iPad 4 Wifi + Cellular", // (model A1460)
@"iPad4,1" :@"iPad Air Wifi", // 5th Generation iPad (iPad Air) - Wifi (model A1474)
@"iPad4,2" :@"iPad Air Wifi + Cellular", // (model A1475)
@"iPad4,3" :@"iPad Air Wifi + Cellular", // (model A1476)
@"iPad4,4" :@"iPad Mini 2 Wifi", // (2nd Generation iPad Mini - Wifi)
@"iPad4,5" :@"iPad Mini 2 Wifi + Cellular", // (2nd Generation iPad Mini - Cellular) (model A1490)
@"iPad4,6" :@"iPad Mini 2 Wifi + Cellular", // (2nd Generation iPad Mini - Cellular) (model A1491)
@"iPad4,7" :@"iPad Mini 3 Wifi", // 3rd Generation iPad Mini - Wifi (model A1599)
@"iPad4,8" :@"iPad Mini 3 Wifi + Cellular", // 3rd Generation iPad Mini - Wifi + Cellular (model A1600)
@"iPad4,9" :@"iPad Mini 3 Wifi + Cellular", // 3rd Generation iPad Mini - Wifi + Cellular (model A1601)
@"iPad5,1" :@"iPad Mini 4 Wifi", // 4th Generation iPad Mini - Wifi (model A1538)
@"iPad5,2" :@"iPad Mini 4 Wifi + Cellular", // 4th Generation iPad Mini - Wifi + Cellular (model A1550)
@"iPad5,3" :@"iPad Air 2 Wifi", // 2nd Generation iPad Air - Wifi (model A1566)
@"iPad5,4" :@"iPad Air 2 Wifi + Cellular ", // 4th Generation iPad Mini - Wifi + Cellular (model A1567)
@"iPad6,3" :@"iPad Pro (9.7\")", // iPad Pro 9.7 inches - (model A1673)
@"iPad6,4" :@"iPad Pro (9.7\")", // iPad Pro 9.7 inches - (models A1674 and A1675)
@"iPad6,7" :@"iPad Pro (12.9\")", // iPad Pro 12.9 inches - (model A1584)
@"iPad6,8" :@"iPad Pro (12.9\")", // iPad Pro 12.9 inches - (model A1652)
@"iPad6,11" :@"iPad 5 Wifi", // iPad (5th Generation) - (model A1822)
@"iPad6,12" :@"iPad 5 Wifi + Cellular", // iPad (5th Generation) - (model A1823)
@"iPad7,1" :@"iPad Pro 2 (12.9\") Wifi", // iPad Pro (12.9") 2nd Generation - (model A1670)
@"iPad7,2" :@"iPad Pro 2 (12.9\") Wifi + Cellular", // iPad Pro (12.9") 2nd Generation - (model A1671 - model A1821)
@"iPad7,3" :@"iPad Pro (10.5\") Wifi", // iPad (5th Generation) - (model A1701)
@"iPad7,4" :@"iPad Pro (10.5\") Wifi + Cellular", // iPad (5th Generation) - (model A1709)
@"Watch1,1" :@"Apple Watch 38mm", // Apple Watch 38mm case
@"Watch1,2" :@"Apple Watch 38mm", // Apple Watch 38mm case
@"Watch2,3" :@"Apple Watch Series 2 38mm", // Apple Watch Series 2 38mm case
@"Watch2,4" :@"Apple Watch Series 2 42mm", // Apple Watch Series 2 42mm case
@"Watch2,6" :@"Apple Watch Series 1 38mm", // Apple Watch Series 1 38mm case
@"Watch2,7" :@"Apple Watch Series 1 42mm", // Apple Watch Series 1 42mm case
@"Watch3,1" :@"Apple Watch Series 3 38mm (GPS+Cellular)", // Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" :@"Apple Watch Series 3 42mm (GPS+Cellular)", // Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" :@"Apple Watch Series 3 38mm (GPS)", // Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" :@"Apple Watch Series 3 42mm (GPS)", // Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" :@"Apple Watch Series 4 40mm (GPS)", // Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" :@"Apple Watch Series 4 44mm (GPS)", // Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" :@"Apple Watch Series 4 40mm (GPS+Cellular)", // Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" :@"Apple Watch Series 4 44mm case (GPS+Cellular)" // Apple Watch Series 4 44mm case (GPS+Cellular)
};
}

NSString* deviceName = [deviceNamesByCode objectForKey:code];

if (!deviceName) {
// Not found on database. At least guess main device type from string contents:

if ([code rangeOfString:@"iPod"].location != NSNotFound) {
deviceName = @"iPod Touch";
}
else if([code rangeOfString:@"iPad"].location != NSNotFound) {
deviceName = @"iPad";
}
else if([code rangeOfString:@"iPhone"].location != NSNotFound){
deviceName = @"iPhone";
}
else {
deviceName = @"Unknown";
}
}

return deviceName;
}
#end if


                                

iOS - B4i

TAGS : iphone model, model
image
Play SystemSounds (and Vibration)

add to region attributes : #IgnoreWarnings: 32

2022-02-16 19:08:25 by Omar
Original Link Author Link
                                    

Sub PlaySystemSound(id As Int)
    Dim NativeMe As NativeObject = Me
    NativeMe.RunMethod("play:", Array(id))
End Sub
#If ObjC
#import 
- (void) play: (int) id{
  AudioServicesPlaySystemSound(id);
}
#End If


                                

iOS - B4i

TAGS : system sounds, sound
image
Detect QR Code from image

2022-02-16 19:10:09 by Omar
Original Link Author Link
                                    

Dim no As NativeObject = Me
Dim res As List = no.RunMethod("detectQR:", Array(LoadBitmap(xui.DefaultFolder, "image.jpeg")))
           
For Each feature As NativeObject In res
    Log(feature.GetField("messageString").AsString)
Next

#if OBJC
@import CoreImage;
- (NSArray*) detectQR: (UIImage*)img {
int exifOrientation;
switch (img.imageOrientation) {
  case UIImageOrientationUp:
  exifOrientation = 1;
  break;
  case UIImageOrientationDown:
  exifOrientation = 3;
  break;
  case UIImageOrientationLeft:
  exifOrientation = 8;
  break;
  case UIImageOrientationRight:
  exifOrientation = 6;
  break;
  case UIImageOrientationUpMirrored:
  exifOrientation = 2;
  break;
  case UIImageOrientationDownMirrored:
  exifOrientation = 4;
  break;
  case UIImageOrientationLeftMirrored:
  exifOrientation = 5;
  break;
  case UIImageOrientationRightMirrored:
  exifOrientation = 7;
  break;
  default:
  break;
}

NSDictionary *detectorOptions = @{ CIDetectorAccuracy : CIDetectorAccuracyHigh };
CIDetector *faceDetector = [CIDetector detectorOfType:CIDetectorTypeQRCode  context:nil options:detectorOptions];

NSArray *features = [faceDetector featuresInImage:[CIImage imageWithCGImage:img.CGImage]
  options:@{CIDetectorImageOrientation:[NSNumber numberWithInt:exifOrientation]}];

  return features;

}
#end if


                                

iOS - B4i

TAGS : qr,detect