Android Question Error When Downloading and save to phone gallery

Makumbi

Well-Known Member
Licensed User
Please help me out iam trying to download that image and then save to my phone gallery but it gives errors below and on checking the gallery there is nothing like the download image

B4X:
Sub Button1_Click
    DownloadAndSaveFile("http://kccug.com/KabojjaApp/work/P1.png")
End Sub



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
    '    If j.Success Then
            Log("Current link: " & Link)
            Log(j.GetString)
    '    End If
    End If
    j.Release
End Sub



Iam seeing this error below

B4X:
** Activity (main) Pause, UserClosed = false **
** Activity (downloadwork) Create, isFirst = true **
** Activity (downloadwork) Resume **
Sleep not resumed (context is paused): b4a.example3.customlistview$ResumableSub_PanelClickHandler
Current link: http://kccug.com/KabojjaApp/work/P1.png
�PNG

������
IHDR�����������������WƳ������gAMA�������a������sRGB����������� cHRM����z&�����������������������u0�����`����:�����p��Q<������bKGD�������������������    pHYs����������������c���������IDATx������:�/�ԂZPjA-���9W
:Q�ęơ3�dy�k����?��    ���|g��{ϻ�H H�C�������������������(������������R�������������������������@ �����������@
��������������������������������������H���������� ��������������������������)������������R������������ �����������@ ������������)������������R�������������������������@ �����������@
��������������������������������������H���������� ��������������������������)������������H���������� �����������@ ������������)������������R�������������������������@ �����������@
��������������������������������������H���������� ��������������������������)������������H���������� �����������@ ������������)������������R�������������������������@ �����������@
��������������������������������������H�����������@
�������������������������)������������H���������� �����������@ ������������)������������R�������������������������@ �����������@
��������������B������������@ �����������@
������������R�������������������������H�����������@
�������������������������)������������H���������� �����������@ ������������)������������R������������ �����������@ �����������@
������������R�������������������������H�����������@
�������������������������)������������H���������� ��@�������?�?������?�Mu���L����������Hmg�1�L9.��q�7���M WN�?�m0��        o�f��.���u]*�������S.M��\��l�j��S�M��]��˙m���F���[=?���������^��������@ �-��}�7�Tպ?��C���C��^#~�]�����f�~U��Kg[�"�\� �u�D��+�_)u~$��͜
��������H�c 58 +��F5    ��ĄR�o�{�H]s��#!�C{\<�/��D��m���:?�3����������@ �U��ɒ}���~�����)��=�K 5v<���؍}����Ȣ0�]�o��j�#�J�0S
��������R�H��
��*P����h=%�VIpߵ�}m�;g��L���_XVcK��"c�\|�'�^v3C�]ư����V8?^����������H�
'�rl������c��\S������.۵@J��4�\�69�^�#�;;vB��H�t��v��]�/��q���9�wK��������@J %��U&���"����;��7=m�V2�jgc-Z�lb�>�@ޙk��v<4����o��0��w��[0��Ɩ�H�������������#��[.�3|��vg/�
��A�k�[aXq�HMl�����@�J(ߡ`d?����=4;�b u˳���-,�[��~�����-�o��o�6�?if��̧��=-���#qY�K�s��������Rl&�jèg�o�E���c��$�J�N�;��1�[���~�hA���g�@��R9w����v����f�ݬ*�f�̹�P%�o�f�ǎ�ϏԀy$ 5C
��������RoH=�f^��,�5�<#����{�v���E�����v��e`i�YKf�!�
�۹:7�g�D.��-*ms2(|N���L��h��K�=�.1��������)�Pz�}l�ŵg��� kl���f�cJ�Ut;#K��&��VcFC����3{n u�t�H5��Q��@(�Lm��6�s���@�^K�#m�?�mh>R�:��������R[��fR���c�T���
�� "�,���T�2�Ҁ�~#g 5R��˺
�P�]���G��m{�,��:Zx~�f̜���0��������@ ��@�i��]��������s�L�cb�s;����
���2�-Y�m�l�������q�C�)2���eF�|E��ж�1�:P�s�G��� �2;
��������RH�a�ɓ��3����%��K�QSk��y�K�
�cD���P�󭡡��F�
Message longer than Log limit (4000). Message was truncated.
 

Makumbi

Well-Known Member
Licensed User
it's a PNG file then you should save it as a PNG file and not DAT

i have changed it to this but when i check on my phone gallery iam not seeing the downloaded file please help
B4X:
#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Spinner1 As Spinner
    Private imageview1 As ImageView
    Dim Button1 As Button
    'Private imageview2 As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Downloadhomework")
    Activity.Title="Homework DownloadLoader"
   
     InitSpinners
End Sub

Sub Activity_Resume

End Sub

Sub InitSpinners
    Private i As Int
    Private Query1 As String
    Private Curs As Cursor
    'query = "CREATE TABLE SMSlist (Account Text, Names Text,Phone text,Sex, ID INTEGER )"
    'We execute a query for each column and fill the Spinner
    'We use SELECT DISTINCT to have each existing first name in the database only once
    Query1 = "SELECT DISTINCT Class FROM Classes where CLASS NOT LIKE '%S%' ORDER BY Class ASC"
    Curs = Starter.SQL1.ExecQuery(Query1)
    'we add 'no filter' as no selection
    Spinner1.Clear
    Spinner1.Add("Select from the List...")
   
    'we fill the Spinner with the data from the database
    For i = 0 To Curs.RowCount - 1
        Curs.Position = i
        'spnFirstName.Add(Curs.GetString("Account"))
        Spinner1.Add(Curs.GetString("Class"))
       
        'Dim kk As String = Curs.GetString("Names")
        'Log(kk)
    Next
    'spnFirstName.RemoveAt("Select from the List...")
    Curs.Close
   
End Sub
Sub Activity_Pause (UserClosed As Boolean)

End Sub




Sub Button1_Click

   
    DownloadImage("http://kccug.com/KabojjaApp/work/P1.png", imageview1)
   
    ProgressDialogShow2("Downloading Home Work Please Wait...",False)
    Sleep(0)'saveimage
    'ProgressDialogHide
End Sub




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
       
       
        Dim bmp As Bitmap = j.GetBitmap
        Dim out As OutputStream
        out = File.OpenOutput(File.DirInternal, "Homework.PNG", False)
        bmp.WriteToStream(out, 100, "PNG")
        out.Close
           
        'This is how you can show it to your gallery
        Dim Phone As Phone
        Dim i As Intent
        i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & File.Combine(File.DirInternal, "Homework.PNG"))
        Phone.SendBroadcastIntent(i)
           
    End If
    j.Release
    ProgressDialogHide
    Sleep(0)'saveima
    MsgboxAsync("Your Homework Has been Downloaded to Your Phone Gallery Please Close and Check your Gallery","Homework Downloaded")
    Sleep(30)'saveimag
End Sub



Public Sub BytesToImage(bytes() As Byte) As Bitmap
    Dim In As InputStream
    In.InitializeFromBytesArray(bytes, 0, bytes.Length)
    Dim bmp As Bitmap
    bmp.Initialize2(In)
    Return bmp
End Sub

Public Sub ImageToBytes(Image As Bitmap) As Byte()
    Dim out As OutputStream
    out.InitializeToBytesArray(0)
    Image.WriteToStream(out, 100, "JPEG")
    out.Close
    Return out.ToBytesArray
End Sub
 
Upvote 0

mangojack

Well-Known Member
Licensed User
Longtime User
Please help me out iam trying to download that image and then save to my phone gallery but it gives errors below and on checking the gallery there is nothing like the download image



Its amazing what you find from a quick search ...

from this post by @Erel , https://www.b4x.com/android/forum/threads/show-image-in-gallery-android-7-0.97662/post-615939 .
I managed to get this to work ... downloading your image.

note: requires RuntimePermissions lib.

*** I could only get it to work by first copying the downloaded image to DirRootExternal folder, I cannot explain as I do not know the reason .. maybe someone else
can jump in and correct any incorrect code.


B4X:
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.png", False)
        File.Copy2(j.GetInputStream, out)
        out.Close
              
        Dim rp As RuntimePermissions
        rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result Then
            File.Copy(File.DirInternal, "filename.png", File.DirRootExternal, "Pictures/filename.png")
            Dim FilePath As String = File.Combine(File.DirRootExternal, "Pictures/filename.png")
            Dim Phone As Phone
            If Phone.SdkVersion <= 18 Then           ' min - 4.3.1
                Dim i As Intent
                i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & FilePath)
                Phone.SendBroadcastIntent(i)
            Else
                Dim ctxt As JavaObject
                ctxt.InitializeContext
                Dim MediaScannerConnection As JavaObject
                MediaScannerConnection.InitializeStatic("android.media.MediaScannerConnection")
                Dim interface As Object = MediaScannerConnection.CreateEventFromUI("android.media.MediaScannerConnection.OnScanCompletedListener", "ScanCompleted", _
                   Null)
                MediaScannerConnection.RunMethod("scanFile", Array(ctxt, Array As String(FilePath), Array As String("image/jpeg"), interface))
            End If
        End If
      
    End If
    j.Release
  
End Sub


ps. I know you were still having problems with this ... so why not post your current problems / errors for all to see.
 
Last edited:
Upvote 0

Makumbi

Well-Known Member
Licensed User
Its amazing what you find from a quick search ...

from this post by @Erel , https://www.b4x.com/android/forum/threads/show-image-in-gallery-android-7-0.97662/post-615939 .
I managed to get this to work ... downloading your image.

note: requires RuntimePermissions lib.

*** I could only get it to work by first copying the downloaded image to DirRootExternal folder, I cannot explain as I do not know the reason .. maybe someone else
can jump in and correct any incorrect code.


B4X:
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.png", False)
        File.Copy2(j.GetInputStream, out)
        out.Close
             
        Dim rp As RuntimePermissions
        rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result Then
            File.Copy(File.DirInternal, "filename.png", File.DirRootExternal, "Pictures/filename.png")
            Dim FilePath As String = File.Combine(File.DirRootExternal, "Pictures/filename.png")
            Dim Phone As Phone
            If Phone.SdkVersion <= 18 Then           ' min - 4.3.1
                Dim i As Intent
                i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & FilePath)
                Phone.SendBroadcastIntent(i)
            Else
                Dim ctxt As JavaObject
                ctxt.InitializeContext
                Dim MediaScannerConnection As JavaObject
                MediaScannerConnection.InitializeStatic("android.media.MediaScannerConnection")
                Dim interface As Object = MediaScannerConnection.CreateEventFromUI("android.media.MediaScannerConnection.OnScanCompletedListener", "ScanCompleted", _
                   Null)
                MediaScannerConnection.RunMethod("scanFile", Array(ctxt, Array As String(FilePath), Array As String("image/jpeg"), interface))
            End If
        End If
     
    End If
    j.Release
 
End Sub


ps. I know you were still having problems with this ... so why not post your current problems / errors for all to see.

right now it is not giving any errors but on checking my phone gallery there is nothing like the saved image
below is the new code adjusted as per your advise
B4X:
#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Spinner1 As Spinner
    Private imageview1 As ImageView
    Dim Button1 As Button
    'Private imageview2 As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Downloadhomework")
    Activity.Title="Homework DownloadLoader"
    
     InitSpinners
End Sub

Sub Activity_Resume

End Sub

Sub InitSpinners
    Private i As Int
    Private Query1 As String
    Private Curs As Cursor
    'query = "CREATE TABLE SMSlist (Account Text, Names Text,Phone text,Sex, ID INTEGER )"
    'We execute a query for each column and fill the Spinner
    'We use SELECT DISTINCT to have each existing first name in the database only once
    Query1 = "SELECT DISTINCT Class FROM Classes where CLASS NOT LIKE '%S%' ORDER BY Class ASC"
    Curs = Starter.SQL1.ExecQuery(Query1)
    'we add 'no filter' as no selection
    Spinner1.Clear
    Spinner1.Add("Select from the List...")
    
    'we fill the Spinner with the data from the database
    For i = 0 To Curs.RowCount - 1
        Curs.Position = i
        'spnFirstName.Add(Curs.GetString("Account"))
        Spinner1.Add(Curs.GetString("Class"))
        
        'Dim kk As String = Curs.GetString("Names")
        'Log(kk)
    Next
    'spnFirstName.RemoveAt("Select from the List...")
    Curs.Close
    
End Sub
Sub Activity_Pause (UserClosed As Boolean)

End Sub

 


Sub Button1_Click

    
'    DownloadImage("http://kccug.com/KabojjaApp/work/P1.png", imageview1)
    
    DownloadAndSaveFile("http://kccug.com/KabojjaApp/work/P1.png")
    
    ProgressDialogShow2("Downloading Home Work Please Wait...",False)
    Sleep(0)'saveimage
    'ProgressDialogHide
End Sub


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, "Homework.PNG", False)
        File.Copy2(j.GetInputStream, out)
        out.Close
              
        Dim rp As RuntimePermissions
        rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result Then
            File.Copy(File.DirInternal, "Homework.PNG", File.DirRootExternal, "Pictures/Homework.PNG")
            Dim FilePath As String = File.Combine(File.DirRootExternal, "Pictures/filename.png")
            Dim Phone As Phone
            If Phone.SdkVersion <= 18 Then           ' min - 4.3.1
                Dim i As Intent
                i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & FilePath)
                Phone.SendBroadcastIntent(i)
            Else
                Dim ctxt As JavaObject
                ctxt.InitializeContext
                Dim MediaScannerConnection As JavaObject
                MediaScannerConnection.InitializeStatic("android.media.MediaScannerConnection")
                Dim interface As Object = MediaScannerConnection.CreateEventFromUI("android.media.MediaScannerConnection.OnScanCompletedListener", "ScanCompleted", _
                   Null)
                MediaScannerConnection.RunMethod("scanFile", Array(ctxt, Array As String(FilePath), Array As String("image/jpeg"), interface))
            End If
        End If
      
    End If
    j.Release
    MsgboxAsync("Your Homework Has been Downloaded to Your Phone Gallery Please Close and Check your Gallery","Homework Downloaded")
    Sleep(30)'saveimag
End Sub

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
        
        
        Dim bmp As Bitmap = j.GetBitmap
        Dim out As OutputStream
        out = File.OpenOutput(File.DirInternal, "Homework.PNG", False)
        bmp.WriteToStream(out, 100, "PNG")
        out.Close
            
        'This is how you can show it to your gallery
        Dim Phone As Phone
        Dim i As Intent
        i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & File.Combine(File.DirInternal, "Homework.PNG"))
        Phone.SendBroadcastIntent(i)
            
    End If
    j.Release
    ProgressDialogHide
    Sleep(0)'saveima
    MsgboxAsync("Your Homework Has been Downloaded to Your Phone Gallery Please Close and Check your Gallery","Homework Downloaded")
    Sleep(30)'saveimag
End Sub



Public Sub BytesToImage(bytes() As Byte) As Bitmap
    Dim In As InputStream
    In.InitializeFromBytesArray(bytes, 0, bytes.Length)
    Dim bmp As Bitmap
    bmp.Initialize2(In)
    Return bmp
End Sub

Public Sub ImageToBytes(Image As Bitmap) As Byte()
    Dim out As OutputStream
    out.InitializeToBytesArray(0)
    Image.WriteToStream(out, 100, "JPEG")
    out.Close
    Return out.ToBytesArray
End Sub
 
Upvote 0

Makumbi

Well-Known Member
Licensed User
Its amazing what you find from a quick search ...

from this post by @Erel , https://www.b4x.com/android/forum/threads/show-image-in-gallery-android-7-0.97662/post-615939 .
I managed to get this to work ... downloading your image.

note: requires RuntimePermissions lib.

*** I could only get it to work by first copying the downloaded image to DirRootExternal folder, I cannot explain as I do not know the reason .. maybe someone else
can jump in and correct any incorrect code.


B4X:
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.png", False)
        File.Copy2(j.GetInputStream, out)
        out.Close
             
        Dim rp As RuntimePermissions
        rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result Then
            File.Copy(File.DirInternal, "filename.png", File.DirRootExternal, "Pictures/filename.png")
            Dim FilePath As String = File.Combine(File.DirRootExternal, "Pictures/filename.png")
            Dim Phone As Phone
            If Phone.SdkVersion <= 18 Then           ' min - 4.3.1
                Dim i As Intent
                i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "file://" & FilePath)
                Phone.SendBroadcastIntent(i)
            Else
                Dim ctxt As JavaObject
                ctxt.InitializeContext
                Dim MediaScannerConnection As JavaObject
                MediaScannerConnection.InitializeStatic("android.media.MediaScannerConnection")
                Dim interface As Object = MediaScannerConnection.CreateEventFromUI("android.media.MediaScannerConnection.OnScanCompletedListener", "ScanCompleted", _
                   Null)
                MediaScannerConnection.RunMethod("scanFile", Array(ctxt, Array As String(FilePath), Array As String("image/jpeg"), interface))
            End If
        End If
     
    End If
    j.Release
 
End Sub


ps. I know you were still having problems with this ... so why not post your current problems / errors for all to see.

Thank you for your effort it has finally work after a long period of suffering you have saved me sleepless nights
 
Upvote 0
Top