Android Question (SOLVE)error open PDF file with android 7+

Discussion in 'Android Questions' started by Mikel Huerta, Sep 21, 2018.

Thread Status:
Not open for further replies.
  1. Mikel Huerta

    Mikel Huerta Member Licensed User

    Hello , i try to open a PDF file from my app on an android 7 with the new permissions functions but when i try to do it, i get this error and a blank screen for a while and nothing more :
    i am using b4a 8.50
    My code :

    Code:
    Sub Doit()
            
    Dim Mostrador_de_PDF As Intent
       
            
    Dim uri As Object
            
    Dim p As Phone
            
    Dim Shared As String
            Shared = rp.GetSafeDirDefaultExternal(
    "shared")
           
                    
    If p.SdkVersion >= 24 Then
                        
    'uri =  rp.GetSafeDirDefaultExternal("shared"), "VM_" & Vars.Datos_Recibo.Remision & ".pdf"
                        uri = CreateFileProviderUri(Shared,   "VM_" & Vars.Datos_Recibo.Remision & ".pdf")
                    
    Else
                        
    uri = "file://" & File.Combine(Shared, "VM_" & Vars.Datos_Recibo.Remision & ".pdf")
                    
    End If
        
       
            BITA(
    "Va a mostrar PDF :" & Vars.Datos_Recibo.Remision)
            Mostrador_de_PDF.Initialize(Mostrador_de_PDF.ACTION_VIEW,  
    uri)
            Mostrador_de_PDF.PutExtra(
    "android.intent.extra.STREAM"uri)
            Mostrador_de_PDF.SetType(
    "application/pdf")
            Mostrador_de_PDF.Flags = 
    1      
       
            
    StartActivity(Mostrador_de_PDF)
    end sub

    sub CreateFileProviderUri (Dir As String, FileName As StringAs Object
        
    Dim FileProvider As JavaObject
        
    Dim context As JavaObject
        context.InitializeContext
        FileProvider.InitializeStatic(
    "android.support.v4.content.FileProvider")
        
    Dim f As JavaObject
        f.InitializeNewInstance(
    "java.io.File"Array(Dir, FileName))
        
        
    Return FileProvider.RunMethod( "getUriForFile"Array(context, Application.PackageName & ".provider", f))     < --- HERE THERE ERROR and dont know why ...
       
    End Sub

    Code:
    Return FileProvider.RunMethod("getUriForFile"Array(context, Application.PackageName & ".provider", f))   'ERROR HERE
    i have android 7 on moto g5

    The error :

    Code:
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
    My manifest
    Code:
    SetApplicationAttribute(android:icon, "@drawable/icon")
    SetApplicationAttribute(android:
    label"$LABEL$")

    AddManifestText(
    <uses-sdk android:minSdkVersion=
    "18" android:targetSdkVersion="26"/>
    <uses-feature android:name=
    "android.hardware.location.gps"/>

    <provider

      android:name=
    "android.support.v4.content.FileProvider"
      android:authorities=
    "$PACKAGE$.provider"
      android:exported=
    "false"
      android:grantUriPermissions=
    "true">
     
    </provider>

    <meta-data
      android:name=
    "android.support.FILE_PROVIDER_PATHS"
      android:resource=
    "@xml/provider_paths"/>

    <supports-screens android:largeScreens=
    "true" 
        android:normalScreens=
    "true" 
        android:smallScreens=
    "true" 
        android:anyDensity=
    "true"/>)   
     
    CreateResource(xml, provider_paths,
       <external-files-
    path name="name" path="shared" />
    )

    'End of default text.

    Thanks a lot for all your help.

    (@Erel new threat created, thanks for any help)
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    Please post the full error message from the logs.

    Can you upload a small project with this code?
     
  3. KMatle

    KMatle Expert Licensed User

    This works for me:

    Code:
    Sub ViewPDF (FolderName As String, FileName As String)
        
    File.Copy(FolderName, FileName, Starter.shared, FileName)
        
    Dim Intent1 As Intent
        Intent1.Initialize(Intent1.ACTION_VIEW, CreateFileProviderUri(Starter.shared, FileName))
        Intent1.SetType(
    "application/pdf")
        Intent1.Flags = 
    1

        
    Try
            
    StartActivity(Intent1)
        
    Catch
            MsgboxAsync(
    "No App to show PDF's installed...." & CRLF & CRLF &  LastException,"Error showing PDF's")
        
    End Try
        
    End Sub

    Sub Share_Click
        
    Dim rp As RuntimePermissions
        
    If File.Exists(rp.GetSafeDirDefaultExternal(""), "Kreditverlauf.pdf") = False Then
           MsgboxAsync(
    "Bitte erst eine Berechnung durchführen","Berechnung fehlt")
           
    Return
        
    End If
        SharePDF(rp.GetSafeDirDefaultExternal(
    ""), "Kreditverlauf.pdf")
        
    End Sub

    Sub SharePDF (FolderName As String, FileName As String)
        
    File.Copy(FolderName, FileName, Starter.shared, FileName)
        
    Dim in As Intent
        
    in.Initialize(in.ACTION_SEND, "")
        
    in.SetType("text/plain")
        
    Log(CreateFileProviderUri(Starter.shared & "/", FileName))
        
    in.PutExtra("android.intent.extra.STREAM",  CreateFileProviderUri(Starter.shared, FileName))
        
    in.Flags = 1
        
    StartActivity(in)
    End Sub

    Sub CreateFileProviderUri (Dir As String, FileName As StringAs Object
        
    Dim FileProvider As JavaObject
        
    Dim context As JavaObject
        context.InitializeContext
        FileProvider.InitializeStatic(
    "android.support.v4.content.FileProvider")
        
    Dim f As JavaObject
        f.InitializeNewInstance(
    "java.io.File"Array(Dir, FileName))
        
    Return FileProvider.RunMethod("getUriForFile"Array(context, Application.PackageName & ".provider", f))
    End Sub
    Manifest

    Code:
    'This code will be applied to the manifest file during compilation.
    'You do not need to modify it in most cases.
    'See this link for for more information: http://www.b4x.com/forum/showthread.php?p=78136
    AddManifestText(
    <uses-sdk android:minSdkVersion=
    "5" android:targetSdkVersion="26"/>
    <supports-screens android:largeScreens=
    "true" 
        android:normalScreens=
    "true" 
        android:smallScreens=
    "true" 
        android:anyDensity=
    "true"/>)
    SetApplicationAttribute(android:icon, 
    "@drawable/icon")
    SetApplicationAttribute(android:
    label"$LABEL$")
    'End of default text.

    'For older Android versions
    AddManifestText(
    <uses-permission
      android:name=
    "android.permission.WRITE_EXTERNAL_STORAGE"
      android:maxSdkVersion=
    "18" />
    )

    AddActivityText(Main,
    <
    intent-filter>
      <action android:name=
    "android.intent.action.PICK" />
      <category android:name=
    "android.intent.category.DEFAULT" />
      <data android:mimeType=
    "image/*" />
    </
    intent-filter>
    <
    intent-filter>
      <action android:name=
    "android.intent.action.GET_CONTENT" />
      <category android:name=
    "android.intent.category.DEFAULT" />
      <category android:name=
    "android.intent.category.OPENABLE" />
      <data android:mimeType=
    "application/pdf" />
    </
    intent-filter>
    )

    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,
       <external-files-
    path name="name" path="shared" />
    )
     
    Erel likes this.
  4. Mikel Huerta

    Mikel Huerta Member Licensed User

    Hello @Erel , thanks for you answer, sure, here is my mini example with the fail, i have tested with many
    app to open the pdf , not only drive google pdf app, and no success , simply i can't get my pdf document
    on screen, help me please.

    I am uploading the mini example.
     

    Attached Files:

  5. Erel

    Erel Administrator Staff Member Licensed User

    Why are you sharing multiple pdf documents? No app will support it.

    Have you tried KMatle's example?
     
  6. Mikel Huerta

    Mikel Huerta Member Licensed User

    yes, i tried it , but i see is missing some code for example the starter module declaration i guess, and i get no success any way.

    On my example, is just for the example, even if i put just 1 pdf doc, the app is still not working. What can i do for just 1 PDF doc please .
     
  7. Erel

    Erel Administrator Staff Member Licensed User

  8. Mikel Huerta

    Mikel Huerta Member Licensed User

    Ok , i read the example and runs it without problems, but for my need of open a pdf file ,if i chages the 1.bal file to a example.pdf , its not open right. On another hand If i chage type text/plain to application/pdf is the same , its not working. Resuming :text/plain doesnt work , application/pdf even not working.

    On my example app i changes the mime type from application/pdf to text/plain and no, its not working.

    i have 3 differents application to read the pdf and all of them runs ok, but no one appers with the code example to view the pdf file.

    Thanks for more help please.
     
  9. Erel

    Erel Administrator Staff Member Licensed User

    1. Please post the full error message.

    2. Please upload the updated project.
     
  10. Mikel Huerta

    Mikel Huerta Member Licensed User

    Hello mr @Erel , sure , here are the zip files with my tests. One of them is with application/pdf and the other one is with text/plain.

    There is no error message, simply no pdf is open, just display or a blank screen or the system menu to choose an app to open, but
    in all the cases never appears one app to open it, i means, appers google drive, mail, whastapp,, etc,etc, but never a simply "adobe" or any of the
    installed viewers.

    Thanks for your help.
     

    Attached Files:

  11. Mahares

    Mahares Well Known Member Licensed User

    Hello @Mikel Huerta
    I downloaded your pdf project. It worked for me without any changes to it and I was able to share it via email. But if you want to open it using a pdf viewer on your device, you need to have the below in the button click sub:
    Code:
    Sub Button1_Click
        
    'copy the file to the shared folder
        Dim FileToSend As String = "vm_panadis_100.pdf"
        
    File.Copy(File.DirAssets, FileToSend, Starter.shared, FileToSend)  
        
    Dim Intent1 As Intent
        Intent1.Initialize(Intent1.ACTION_VIEW, CreateFileProviderUri(Starter.shared, FileToSend))
        Intent1.SetType(
    "application/pdf")
        Intent1.Flags = 
    1
        
    Try
            
    StartActivity(Intent1)
        
    Catch
            MsgboxAsync(
    "No App to display PDF files is installed on your device...." & CRLF & _
            
    CRLF &  LastException,"Error PDF")
        
    End Try
    End Sub
    I tested and I was able to open it with the pdf viewer when I used the above code.
     
    DKHDKH, Erel and DonManfred like this.
  12. Mikel Huerta

    Mikel Huerta Member Licensed User

    Ok, @Mahares you rules man !!! thank you so much, i have no words to thanks you. Its runs as a charm !!
    Master @Erel thanks too for you help.
     
  13. nickysuwandi

    nickysuwandi Member Licensed User

    Hi all
    i had try this project to open pdf download from web service, but got error "(NullPointerException) java.lang.NullPointerException:Attempt to invoke virtual method android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,jva.lang.String) on a null object reference"

    Anybody can help me,where wrong to my code:

    Code:
    Sub imgdownload_Click
        
    Dim intresult As Int
        intresult=
    Msgbox2("Download Report ??","Download","Yes","Cancell","",Null )
        
    If intresult=DialogResponse.POSITIVE Then
            
    ProgressDialogShow2("Please wait . . .",  True)
            
    Dim job As HttpJob
            job.Initialize(
    "pdf" , Me)
            
    Dim S As String = Starter.serverAddress & "/report.php?usr=" & Starter.strusr & "&psw=" & Starter.strtoken
            job.Download(s)
            
    wait for (job) JobDone (job As HttpJob)
            
    If job.Success = True Then
                
    Try
                    
    Dim out As OutputStream=File.OpenOutput(Starter.shared ,"report.pdf",  False )
                    
    File.Copy2(job.GetInputStream  ,out)
                    out.Close
                    
                    
    Dim Intent1 As Intent
                    Intent1.Initialize(Intent1.ACTION_VIEW, app.CreateFileProviderUri(Starter.shared, 
    "report.pdf"))
                    Intent1.SetType(
    "application/pdf")
                    Intent1.Flags = 
    1
                    
    Try
                        
    StartActivity(Intent1)
                    
    Catch
                        MsgboxAsync(
    "No App to display PDF files is installed on your device...." & CRLF & CRLF &  LastException,"Error PDF")
                    
    End Try

                
    Catch
                    
    Log(LastException)
                
    End Try
            
    End If
            job.Release
            
    ProgressDialogHide
        
    End If
    End Sub
    Thanks
     
  14. Erel

    Erel Administrator Staff Member Licensed User

    You should never post in existing threads.
     
  15. nickysuwandi

    nickysuwandi Member Licensed User

    Hi Erel
    i just found from solution in problem from this thread, but i have trouble to read from downloaded pdf, so i ask in same thread if the are good men to help me. I don't know that this wrong.

     
  16. Erel

    Erel Administrator Staff Member Licensed User

    This is the forum policy. You should always start a new thread for your question. You can post a link to this one if you like.
     
Thread Status:
Not open for further replies.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice