Android Code Snippet 📌 [B4A] Save a file to the Download folder (and document, pictures, music, movies, dcim folders)

Star-Dust

Expert
Licensed User
Longtime User
On LinkedIn there is my next comment that brings to a better version of the code.
Please don't post direct links by Github, if I wanted I would have done it myself. Go to the LinkedIn page
 

Star-Dust

Expert
Licensed User
Longtime User
It is not possible to read in the folder, so you cannot know if it already exists in it can be canceled
 

rogeriosca

Member
Licensed User
Longtime User
Grazie! Funziona perfettamente qui!
 

valerioup

Member
Licensed User
Longtime User
Save in DCIM:
Sub SaveImageToDCIM(bmp As Bitmap, fileName As String)
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    
    Dim values As JavaObject
    values.InitializeNewInstance("android.content.ContentValues", Null)
    values.RunMethod("put", Array("_display_name", fileName)) ' Campo corretto per il nome del file
    values.RunMethod("put", Array("title", fileName)) ' set filename
    values.RunMethod("put", Array("mime_type", "image/jpeg")) ' Tipo MIME corretto
    values.RunMethod("put", Array("relative_path", "DCIM/MyApp")) ' Cartella di destinazione DCIM
    
    Dim resolver As JavaObject = ctxt.RunMethod("getContentResolver", Null)
    Dim uri As JavaObject = resolver.RunMethod("insert", Array(GetMediaStoreImagesUri, values))
    
    If uri.IsInitialized Then
        Dim os As OutputStream = resolver.RunMethod("openOutputStream", Array(uri))
        bmp.WriteToStream(os, 100, "JPEG")
        os.Close
        Log("✅ Immagine salvata in DCIM/MyApp: " & fileName)
        ToastMessageShow("Immagine salvata", True)
    Else
        Log("❌ Errore nel salvataggio dell'immagine")
        ToastMessageShow("ERRORE", True)
    End If
End Sub

Sub GetMediaStoreImagesUri As Object
    Dim jo As JavaObject
    jo.InitializeStatic("android.provider.MediaStore$Images$Media")
    Return jo.GetField("EXTERNAL_CONTENT_URI")
End Sub

A modified version to save to the DCIM folder
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…