Android Question [SOLVED] Download and Open FIle

Puthut Wibowo

Member
Licensed User
I want to download and open the file that I downloaded, I use the following programming code but the error and don't know where the error is

Code:
Sub Class_Globals
    Public rp As RuntimePermissions
    Public SPMIfolder As String=rp.GetSafeDirDefaultExternal("SPMI")
    
End Sub


Private Sub DownloadFile(sLink As String,sFileName As String)
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download(sLink)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim splitta() As String = Regex.Split("\.", sFileName)
            Dim estensione As String = splitta(1)
            Dim out As OutputStream = File.OpenOutput(SPMIfolder, sFileName, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
            Dim apro As Int
            apro = Msgbox2("Do you want Open Document in attachment ?", "Message", "Yes","","No", Null)
            If apro = DialogResponse.POSITIVE Then
                Dim i As Intent
                i.Initialize(i.ACTION_VIEW, "file://" & File.Combine(SPMIfolder, sFileName))
                i.SetComponent("android/com.android.internal.app.ResolverActivity")
                Select estensione
                    Case "pdf"
                        i.SetType("application/pdf")
                        Log("PDF------")
                    Case "docx"
                        i.SetType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    Case "txt"
                        i.SetType("text/plain")
                    Case "jpg"
                        i.SetType("image/jpg")
                    Case "jpeg"
                        i.SetType("image/jpeg")
                End Select
          
                StartActivity(i)
 
            End If


Else
    ToastMessageShow("Error: " & J.ErrorMessage , True)
End If
j.Release

Error Log
B4X:
Error occurred on line: 259 (DocumentDetail)
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/b4a.example/files/SPMI/1605074220_sample (4).pdf exposed beyond app through Intent.getData()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:2141)
    at android.net.Uri.checkFileUriExposed(Uri.java:2391)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11848)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11797)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1722)
    at android.app.Activity.startActivityForResult(Activity.java:5377)
    at android.app.Activity.startActivityForResult(Activity.java:5335)
    at android.app.Activity.startActivity(Activity.java:5721)
    at android.app.Activity.startActivity(Activity.java:5674)
    at anywheresoftware.b4a.keywords.Common.StartActivity(Common.java:857)
    at b4a.example.documentdetail$ResumableSub_DownloadFile.resume(documentdetail.java:677)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resumeAsUserSub(DebugResumableSub.java:48)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:351)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resume(DebugResumableSub.java:43)
    at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:267)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:137)
    at anywheresoftware.b4a.BA$2.run(BA.java:387)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
 

agraham

Expert
Licensed User
Longtime User
Probably because as Erel said here - my boldening
Starting from Android 7 (API 24) you cannot directly share file uris with other applications. You need to use FileProvider.
You need to do it like this
B4X:
 i.Initialize(i.ACTION_VIEW, Provider.GetFileUri(File.Combine(SPMIfolder, sFileName)))
But there are manifest entries needed too. See the post I linked to above.
 
Upvote 0

Puthut Wibowo

Member
Licensed User
Thank you agraham, I've changed my coding and manifest, but it's still an error

Code:
Private Sub DownloadFile(sLink As String,sFileName As String)
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download(sLink)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim splitta() As String = Regex.Split("\.", sFileName)
            Dim estensione As String = splitta(1)
            Dim out As OutputStream = File.OpenOutput(SPMIfolder, sFileName, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
            Dim apro As Int
            apro = Msgbox2("Do you want Open Document in attachment ?", "Message", "Yes","","No", Null)
            If apro = DialogResponse.POSITIVE Then
                Dim i As Intent
                i.Initialize(i.ACTION_VIEW, Starter.Provider.GetFileUri(File.Combine(SPMIfolder, sFileName)))
                i.SetComponent("android/com.android.internal.app.ResolverActivity")
                Select estensione
                    Case "pdf"
                        i.SetType("application/pdf")
                        
                    Case "docx"
                        i.SetType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    Case "txt"
                        i.SetType("text/plain")
                    Case "jpg"
                        i.SetType("image/jpg")
                    Case "jpeg"
                        i.SetType("image/jpeg")
                End Select
          
                StartActivity(i)
 
            End If


Else
    ToastMessageShow("Error: " & J.ErrorMessage , True)
End If
j.Release
ProgressDialogHide
End Sub

Mainfest:
AddManifestText(<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="30" />
)
AddApplicationText(
  <provider
  android:name="android.support.v4.content.FileProvider"
  android:authorities="$PACKAGE$.provider"
  android:exported="false"
  android:grantUriPermissions="true">
  <meta-data
  android:name="android.support.FILE_PROVIDER_PATHS"
  android:resource="@xml/provider_paths"/>
  </provider>
)
CreateResource(xml, provider_paths,
   <files-path name="name" path="shared" />
)

Error Log:
Error occurred on line: 251 (DocumentDetail)
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/b4a.example/files/SPMI/1605074220_sample (4).pdf exposed beyond app through Intent.getData()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:2141)
    at android.net.Uri.checkFileUriExposed(Uri.java:2391)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11848)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11797)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1722)
    at android.app.Activity.startActivityForResult(Activity.java:5377)
    at android.app.Activity.startActivityForResult(Activity.java:5335)
    at android.app.Activity.startActivity(Activity.java:5721)
    at android.app.Activity.startActivity(Activity.java:5674)
    at anywheresoftware.b4a.keywords.Common.StartActivity(Common.java:857)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runVoidMethod(Shell.java:777)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:354)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at anywheresoftware.b4a.shell.DebugResumableSub$RemoteResumableSub.resume(DebugResumableSub.java:22)
    at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:267)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:137)
    at anywheresoftware.b4a.BA$2.run(BA.java:387)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
 
Upvote 0

Puthut Wibowo

Member
Licensed User
After changing the mainfest project, the code error is different, as follows
Error Log:
Error occurred on line: 34 (FileProvider)
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:132)
    at b4a.example.fileprovider._getfileuri(fileprovider.java:87)
    at b4a.example.documentdetail$ResumableSub_DownloadFile.resume(documentdetail.java:600)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resumeAsUserSub(DebugResumableSub.java:48)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:351)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at anywheresoftware.b4a.shell.DebugResumableSub$DelegatableResumableSub.resume(DebugResumableSub.java:43)
    at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:267)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:137)
    at anywheresoftware.b4a.BA$2.run(BA.java:387)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /data/user/0/b4a.example/files/shared/storage/emulated/0/Android/data/b4a.example/files/SPMI/1605080340_Sample_Doc.doc
    at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:744)
    at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:418)
    ... 23 more


Try
B4X:
CreateResource(xml, provider_paths,
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="root" path="" />
</paths>
)
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
That file path is obviously wrong
/data/user/0/b4a.example/files/shared/storage/emulated/0/Android/data/b4a.example/files/SPMI/1605080340_Sample_Doc.doc
I would expect something like
/storage/emulated/0/Android/data/b4a.example/files/SPMI/1605080340_Sample_Doc.doc
Where is that prefix coming from?
 
Upvote 0

Puthut Wibowo

Member
Licensed User
I think from the following sub-programs
B4X:
' PROJECT MANIFEST
CreateResource(xml, provider_paths,
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
  [B]  <external-path name="root" path="" />[/B]
</paths>
)


Private Sub B4XPage_Created (Root1 As B4XView)   
 Public rp As RuntimePermissions
[B] SPMIfolder =rp.GetSafeDirDefaultExternal("SPMI")[/B]
    
End Sub



Private Sub DownloadFile(sLink As String,sFileName As String)
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download(sLink)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim splitta() As String = Regex.Split("\.", sFileName)
        Dim estensione As String = splitta(1)
        
        [B]Dim out As OutputStream = File.OpenOutput(SPMIfolder, sFileName, False)[/B]
        File.Copy2(j.GetInputStream, out)
        
        out.Close '<------ very important
        Dim apro As Int
        apro = Msgbox2("Do you want Open Document in attachment ?", "Message", "Yes","","No", Null)
        If apro = DialogResponse.POSITIVE Then
            Dim i As Intent
            
          [B]  i.Initialize(i.ACTION_VIEW, Starter.Provider.GetFileUri(File.Combine(SPMIfolder, sFileName)))[/B]
            
            i.SetComponent("android/com.android.internal.app.ResolverActivity")
            Select estensione
                Case "pdf"
                    i.SetType("application/pdf")
                        
                Case "docx"
                    i.SetType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                Case "txt"
                    i.SetType("text/plain")
                Case "jpg"
                    i.SetType("image/jpg")
                Case "jpeg"
                    i.SetType("image/jpeg")
            End Select
          
            StartActivity(i)
 
        End If


    Else
        ToastMessageShow("Error: " & J.ErrorMessage , True)
    End If
    j.Release
    ProgressDialogHide
End Sub
 
Upvote 0

Puthut Wibowo

Member
Licensed User
I've tried tracing from the download process to the file provide

Here I attach the file from downloading to opening the file uri
 

Attachments

  • B4ADownloadandOpen.zip
    11.9 KB · Views: 91
Upvote 0

Puthut Wibowo

Member
Licensed User
Finally I can find the problem
The following is a running program code (see attachment).

Download using okhttps2 and open the file with FileProvider

Thanks Agraham for your Help
 

Attachments

  • Download and Open File Provider.zip
    10.4 KB · Views: 136
Upvote 0
Top