Xamarin.Forms Android FileProvider: Java.Lang.NullPointerException when trying to read file
I've been trying generate word files and open it on an Android using Xamarin.Forms. I can create the file, but the following error is thrown when I try to read:
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
The code I'm using is as follows:
The AndroidManifest.xml contains:
<application>
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.ESFJP.ESFAtas.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/>
</provider>
</application>
The provider_paths.xml, which lies in the folder Resources/xml, is:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="/Atas"/>
<files-path name="files" path="/Atas"/>
</paths>
The async method to save the file and open:
public async Task Save(string fileName, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string root = null;
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new Java.IO.File(root + "/Atas");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists()) file.Delete();
try
{
//The permission failure happens in this line when the target version is set to API Level 27 Nougat
FileOutputStream outs = new FileOutputStream(file);
stream.Position = 0;
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
//The permission failure can be seen here if the target version is set to API level 27 Nougat
exception = e.ToString();
}
finally
{
stream.Dispose();
}
if (file.Exists())
{
string auth = "com.ESFJP.ESFAtas.fileprovider";
string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Uri.FromFile(file).ToString());
string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if (mimeType == null)
mimeType = "*/*";
//The Java.Lang.NullPointerException is thrown from this line ///
Uri uri = FileProvider.GetUriForFile(Forms.Context, auth, file);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission);
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
var resInfoList = Forms.Context.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
foreach (var resolveInfo in resInfoList)
{
var packageName = resolveInfo.ActivityInfo.PackageName;
Forms.Context.GrantUriPermission(packageName, uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantPrefixUriPermission | ActivityFlags.GrantReadUriPermission);
}
Forms.Context.StartActivity(intent);
}
}
I've been struggling with this code. Many threads told about the issue being on the provider_paths.xml, but I can't figure out why or where or even if it's actually there.
EDIT.: in order to reproduce the issue more clearly, I've uploaded a sample to my GitHub here: https://github.com/RaelsonCraftz/XamarinFileProviderSample
Also a small update. If you set the Targed Android version
to Use Compile using SDK version
the app manages to at least create the file, but it won't open, giving the Java.Lang.NullPointerException mentioned above. IF you set it to Android 8.1 (API Level 27 - Oreo), it won't manage to create the file. It says that the permission has not been granted at this line exception = e.ToString();
. I've marked the line where that happens, it's on the public async Task Save(string fileName, string contentType, MemoryStream stream)
.
android xamarin android-intent android-fileprovider
add a comment |
I've been trying generate word files and open it on an Android using Xamarin.Forms. I can create the file, but the following error is thrown when I try to read:
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
The code I'm using is as follows:
The AndroidManifest.xml contains:
<application>
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.ESFJP.ESFAtas.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/>
</provider>
</application>
The provider_paths.xml, which lies in the folder Resources/xml, is:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="/Atas"/>
<files-path name="files" path="/Atas"/>
</paths>
The async method to save the file and open:
public async Task Save(string fileName, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string root = null;
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new Java.IO.File(root + "/Atas");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists()) file.Delete();
try
{
//The permission failure happens in this line when the target version is set to API Level 27 Nougat
FileOutputStream outs = new FileOutputStream(file);
stream.Position = 0;
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
//The permission failure can be seen here if the target version is set to API level 27 Nougat
exception = e.ToString();
}
finally
{
stream.Dispose();
}
if (file.Exists())
{
string auth = "com.ESFJP.ESFAtas.fileprovider";
string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Uri.FromFile(file).ToString());
string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if (mimeType == null)
mimeType = "*/*";
//The Java.Lang.NullPointerException is thrown from this line ///
Uri uri = FileProvider.GetUriForFile(Forms.Context, auth, file);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission);
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
var resInfoList = Forms.Context.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
foreach (var resolveInfo in resInfoList)
{
var packageName = resolveInfo.ActivityInfo.PackageName;
Forms.Context.GrantUriPermission(packageName, uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantPrefixUriPermission | ActivityFlags.GrantReadUriPermission);
}
Forms.Context.StartActivity(intent);
}
}
I've been struggling with this code. Many threads told about the issue being on the provider_paths.xml, but I can't figure out why or where or even if it's actually there.
EDIT.: in order to reproduce the issue more clearly, I've uploaded a sample to my GitHub here: https://github.com/RaelsonCraftz/XamarinFileProviderSample
Also a small update. If you set the Targed Android version
to Use Compile using SDK version
the app manages to at least create the file, but it won't open, giving the Java.Lang.NullPointerException mentioned above. IF you set it to Android 8.1 (API Level 27 - Oreo), it won't manage to create the file. It says that the permission has not been granted at this line exception = e.ToString();
. I've marked the line where that happens, it's on the public async Task Save(string fileName, string contentType, MemoryStream stream)
.
android xamarin android-intent android-fileprovider
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08
add a comment |
I've been trying generate word files and open it on an Android using Xamarin.Forms. I can create the file, but the following error is thrown when I try to read:
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
The code I'm using is as follows:
The AndroidManifest.xml contains:
<application>
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.ESFJP.ESFAtas.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/>
</provider>
</application>
The provider_paths.xml, which lies in the folder Resources/xml, is:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="/Atas"/>
<files-path name="files" path="/Atas"/>
</paths>
The async method to save the file and open:
public async Task Save(string fileName, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string root = null;
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new Java.IO.File(root + "/Atas");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists()) file.Delete();
try
{
//The permission failure happens in this line when the target version is set to API Level 27 Nougat
FileOutputStream outs = new FileOutputStream(file);
stream.Position = 0;
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
//The permission failure can be seen here if the target version is set to API level 27 Nougat
exception = e.ToString();
}
finally
{
stream.Dispose();
}
if (file.Exists())
{
string auth = "com.ESFJP.ESFAtas.fileprovider";
string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Uri.FromFile(file).ToString());
string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if (mimeType == null)
mimeType = "*/*";
//The Java.Lang.NullPointerException is thrown from this line ///
Uri uri = FileProvider.GetUriForFile(Forms.Context, auth, file);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission);
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
var resInfoList = Forms.Context.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
foreach (var resolveInfo in resInfoList)
{
var packageName = resolveInfo.ActivityInfo.PackageName;
Forms.Context.GrantUriPermission(packageName, uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantPrefixUriPermission | ActivityFlags.GrantReadUriPermission);
}
Forms.Context.StartActivity(intent);
}
}
I've been struggling with this code. Many threads told about the issue being on the provider_paths.xml, but I can't figure out why or where or even if it's actually there.
EDIT.: in order to reproduce the issue more clearly, I've uploaded a sample to my GitHub here: https://github.com/RaelsonCraftz/XamarinFileProviderSample
Also a small update. If you set the Targed Android version
to Use Compile using SDK version
the app manages to at least create the file, but it won't open, giving the Java.Lang.NullPointerException mentioned above. IF you set it to Android 8.1 (API Level 27 - Oreo), it won't manage to create the file. It says that the permission has not been granted at this line exception = e.ToString();
. I've marked the line where that happens, it's on the public async Task Save(string fileName, string contentType, MemoryStream stream)
.
android xamarin android-intent android-fileprovider
I've been trying generate word files and open it on an Android using Xamarin.Forms. I can create the file, but the following error is thrown when I try to read:
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
The code I'm using is as follows:
The AndroidManifest.xml contains:
<application>
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.ESFJP.ESFAtas.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/>
</provider>
</application>
The provider_paths.xml, which lies in the folder Resources/xml, is:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="/Atas"/>
<files-path name="files" path="/Atas"/>
</paths>
The async method to save the file and open:
public async Task Save(string fileName, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string root = null;
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new Java.IO.File(root + "/Atas");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists()) file.Delete();
try
{
//The permission failure happens in this line when the target version is set to API Level 27 Nougat
FileOutputStream outs = new FileOutputStream(file);
stream.Position = 0;
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
//The permission failure can be seen here if the target version is set to API level 27 Nougat
exception = e.ToString();
}
finally
{
stream.Dispose();
}
if (file.Exists())
{
string auth = "com.ESFJP.ESFAtas.fileprovider";
string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Uri.FromFile(file).ToString());
string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if (mimeType == null)
mimeType = "*/*";
//The Java.Lang.NullPointerException is thrown from this line ///
Uri uri = FileProvider.GetUriForFile(Forms.Context, auth, file);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission);
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
var resInfoList = Forms.Context.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
foreach (var resolveInfo in resInfoList)
{
var packageName = resolveInfo.ActivityInfo.PackageName;
Forms.Context.GrantUriPermission(packageName, uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantPrefixUriPermission | ActivityFlags.GrantReadUriPermission);
}
Forms.Context.StartActivity(intent);
}
}
I've been struggling with this code. Many threads told about the issue being on the provider_paths.xml, but I can't figure out why or where or even if it's actually there.
EDIT.: in order to reproduce the issue more clearly, I've uploaded a sample to my GitHub here: https://github.com/RaelsonCraftz/XamarinFileProviderSample
Also a small update. If you set the Targed Android version
to Use Compile using SDK version
the app manages to at least create the file, but it won't open, giving the Java.Lang.NullPointerException mentioned above. IF you set it to Android 8.1 (API Level 27 - Oreo), it won't manage to create the file. It says that the permission has not been granted at this line exception = e.ToString();
. I've marked the line where that happens, it's on the public async Task Save(string fileName, string contentType, MemoryStream stream)
.
android xamarin android-intent android-fileprovider
android xamarin android-intent android-fileprovider
edited Nov 14 at 13:15
asked Nov 11 at 13:48
Raelson Craftz
11
11
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08
add a comment |
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249389%2fxamarin-forms-android-fileprovider-java-lang-nullpointerexception-when-trying-t%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249389%2fxamarin-forms-android-fileprovider-java-lang-nullpointerexception-when-trying-t%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Can you please provide sample here, I will test it at my side.
– Cherry Bu
Nov 13 at 9:27
Absolutely! I've provided a link on the original post
– Raelson Craftz
Nov 14 at 13:04
Guys, no clue? Is there anything more I need to provide? I've played a bit with it but I'm still lost as how to solve this issue. PS.: this uses a Syncfusion's library to generate the word document, but apparently the issue happens before the library is even relevant. So I'm not sure if the problem is on their end, must be just the code.
– Raelson Craftz
Dec 18 at 19:08