Ad

Showing PDF-File With MVVM Cross On Android And IOS

I want to open a PDF on the Phone via the File-Path but i cant figure out how i could do this properly without using 3rd party packages.

You have any suggestion for this?

I already tried to use this on Android:

public void OpenFile(string filePath)
{
     var fileToOpen = new Java.IO.File(filePath);

     var uri = FileProvider.GetUriForFile(Application.Context, Application.Context.PackageName + ".fileprovider", fileToOpen);
     var intent = new Intent();
     var mime = IOUtil.GetMimeType(uri.ToString());

     intent.SetAction(Intent.ActionView);
     intent.SetDataAndType(uri, mime);
     intent.SetFlags(ActivityFlags.NewTask);
     intent.AddFlags(ActivityFlags.GrantReadUriPermission);

     Application.Context.StartActivity(intent);
}

But i get the following Error:

Unhandled Exception:

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

Ad

Answer

Your error is telling us that there is no file at the location matching that's passed into the function. There's a few ways of doing this, one of them is as shown. After accepting permissions to access folders and files, this should be one of the simplest ways. You seem to be close:

public void OpenPdfFile(string filename)
{
  var f = new Java.IO.File(filename);
  if (f.Exists())
  {
    System.Diagnostics.Debug.WriteLine("File exists!");
    try
    {
      var openFileIntent = new Intent(Intent.ActionView);
      openFileIntent.SetDataAndType(Android.Net.Uri.FromFile(f), "application/pdf");
      openFileIntent.SetFlags(ActivityFlags.NoHistory);

      StartActivity(Intent.CreateChooser(openFileIntent, "Open pdf file"));
    }
    catch (ActivityNotFoundException)
    {
      //handle when no available apps
    }
  }
}

I haven't tested your work, but the first thing would be to see if you added this to the Manifest file android:authorities="com.{package}.{name}.fileprovider" since your code says Application.Context.PackageName + ".fileprovider"

Ad
source: stackoverflow.com
Ad