Xam.Plugin.Media not working

This is my Xaml (C#):

`private void Xaml()
{
Title = "Incidências";
var Grid = new Grid();
Grid.RowDefinitions = new RowDefinitionCollection();

        //Colunas
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Absolute) });      //0 e 1
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10, GridUnitType.Star) });         //1 e 2
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30, GridUnitType.Absolute) });     //2 e 3
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10, GridUnitType.Star) });         //3 e 4
        Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Absolute) });      //4 e 5

        //Linhas
        //Grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Absolute) });         //0 e 1
        Grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });               //0 e 1
        Grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(150, GridUnitType.Auto) });             //1 e 2
        Grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(75, GridUnitType.Star) });              //2 e 3


        //var width = mainDisplayInfo.Width;
        //var height = mainDisplayInfo.Height / 5;

        myImage = new Image
        {
            Margin = 2,
            HeightRequest = 500,
            WidthRequest = 500,
            BackgroundColor = Color.White,
            Aspect = Aspect.AspectFit,
            VerticalOptions = LayoutOptions.Start,
        };
        myEditor = new Editor
        {
            Margin = 2,
            BackgroundColor = Color.White,
            AutoSize = EditorAutoSizeOption.TextChanges,
            Placeholder = "Descrição do Incidente",
        };

        camera = new Button
        {
            Margin = 10,
            Text = "Camera",
            BackgroundColor = Color.FromHex("#0061B1"),
            TextColor = Color.White,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        gravar = new Button
        {
            Margin = 10,
            Text = "Gravar Incidência",
            BackgroundColor = Color.FromHex("#0061B1"),
            TextColor = Color.White,
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        stack = new StackLayout
        {
            BackgroundColor = Color.FromHex("#0061B1"),
            VerticalOptions = LayoutOptions.End,
            Margin = 1,
            Children =
        {
            myImage
        }
        };
        stack2 = new StackLayout
        {
            BackgroundColor = Color.FromHex("#0061B1"),
            VerticalOptions = LayoutOptions.End,
            Margin = 1,
            Children =
        {
            myEditor
        }
        };

        Grid.Children.Add(stack, 1, 4, 0, 1);
        Grid.Children.Add(stack2, 1, 4, 1, 2);
        Grid.Children.Add(camera, 1, 2, 2, 3);
        Grid.Children.Add(gravar, 3, 4, 2, 3);

        scroll = new ScrollView
        {
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.End,
                Children =
            {
                Grid
            }
            }
        };
        Content = new StackLayout
        {
            Margin = 5,

            Children =
        {
            scroll,
        }
        };
    }`

And I inicialize my button like this:
camera.Clicked += Camera_Clicked;

`private async void Camera_Clicked(object sender, EventArgs e)
{
//App.certeza = 0;
//#region testeCamera
await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await DisplayAlert("Erro!", "A camera já está a ser usada!", "Ok");
            return;
        }

        var files = await CrossMedia.Current.TakeVideoAsync(
            new StoreVideoOptions
            {
                SaveMetaData = true,

        });
        if (files == null)
            return;

        myImage.Source = ImageSource.FromStream(() =>
        {
            var stream = files.GetStream();
            files.Dispose();
            return stream;
        });
        //#endregion
    }`

I already create a folder with my file_paths.xml:
<?xml version="1.0" encoding="utf-8"?> `

And i added this to my AndroidManifest:
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="MY_PACKAGE_NAME.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>

AND THIS ERROR KEEPS APPEARING!
System.ArgumentException: Unable to get file location. This most likely means that the file provider information is not set in your Android Manifest file. Please check documentation on how to set this up in your project.

Any help?

Best Answers

  • JarvanJarvan Xamurai
    Accepted Answer

    @ricardoventura
    Check the follows:

    • Ensure you have added the two nuget packages: Plugin.CurrentActivity and Plugin.Permissions.
    • Add CrossCurrentActivity.Current.Init(this, bundle); in MainActivity.cs
    • Add the code in MainActivity.cs:
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
    {
        PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    I reproduced you code and it works. You can refer to it, here is the demo.

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited June 13

    What's the code of file_paths file? There may be something wrong with the settings in the file.

    Check the link: https://forums.xamarin.com/discussion/119942/mediaplugin-argument-exception-unable-to-get-file-location

  • ricardoventuraricardoventura Member ✭✭

    @yelinzh said:
    What's the code of file_paths file? There may be something with the settings in the file.

    Check the link: https://forums.xamarin.com/discussion/119942/mediaplugin-argument-exception-unable-to-get-file-location

    File_paths's code:
    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.plugin.mediatest/files/Pictures" />
    </paths>

    I already saw that link before posting this one. Didn't work :disappointed:
    Thanks for your replying!

  • ricardoventuraricardoventura Member ✭✭

    @yelinzh said:
    @ricardoventura
    Have you added the provider code in application tag?

    <application android:label="App15.Android">
      <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.fileprovider" android:exported="false" android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
      </provider>
    </application>
    

    Yes, ain't that one that I previously wrote above the error on my first post?

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited May 30

    @ricardoventura
    If you add the code outside the application tag like below, you'll get the error. Please check you code.

    <application android:label="App15.Android">
    </application>
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.fileprovider" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
    </provider>
    
  • ricardoventuraricardoventura Member ✭✭

    @yelinzh said:
    @ricardoventura
    If you add the code outside the application tag like below, you'll get the error. Please check you code.

    <application android:label="App15.Android">
    </application>
      <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.fileprovider" android:exported="false" android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
      </provider>
    

    I have this:

  • JarvanJarvan Member, Xamarin Team Xamurai
    Accepted Answer

    @ricardoventura
    Check the follows:

    • Ensure you have added the two nuget packages: Plugin.CurrentActivity and Plugin.Permissions.
    • Add CrossCurrentActivity.Current.Init(this, bundle); in MainActivity.cs
    • Add the code in MainActivity.cs:
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
    {
        PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    I reproduced you code and it works. You can refer to it, here is the demo.

  • ricardoventuraricardoventura Member ✭✭

    @yelinzh said:
    @ricardoventura
    Test if the following code can work on your project.
    page.xaml

    <StackLayout Spacing="10" Padding="10">
         <Button x:Name="takePhoto" Text="Take Photo"/>
         <Button x:Name="pickPhoto" Text="Pick Photo"/>
         <Image x:Name="image"/>
    </StackLayout>
    

    page.xaml.cs

    public MainPage()
    {
        InitializeComponent();
        takePhoto.Clicked += async (sender, args) =>
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                DisplayAlert("No Camera", ":( No camera available.", "OK");
                return;
            }
            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                Directory = "Test",
                SaveToAlbum = true,
                CompressionQuality = 75,
                CustomPhotoSize = 50,
                PhotoSize = PhotoSize.MaxWidthHeight,
                MaxWidthHeight = 2000,
                DefaultCamera = CameraDevice.Front
            });
            if (file == null)
                return;
    
            DisplayAlert("File Location", file.Path, "OK");
    
            image.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });
        };
        pickPhoto.Clicked += async (sender, args) =>
        {
            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                return;
            }
            var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
    
            });
    
            if (file == null)
                return;
    
            image.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });
        };
    }
    

    I tried everything you put in that post and didn't.. The error stills the same :disappointed:
    Im using permissions for Camera, WriteExternalStorage and ReadExternalStorage... Do i need more?

  • ricardoventuraricardoventura Member ✭✭

    @yelinzh said:
    @ricardoventura
    Check the follows:

    • Ensure you have added the two nuget packages: Plugin.CurrentActivity and Plugin.Permissions.
    • Add CrossCurrentActivity.Current.Init(this, bundle); in MainActivity.cs
    • Add the code in MainActivity.cs:
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
    {
      PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    I reproduced you code and it works. You can refer to it, here is the demo.

    Let me check really fast! Thank you in advance!

  • JarvanJarvan Member, Xamarin Team Xamurai

    @ricardoventura
    You can refer to the demo I posted. Or could you sharing a basic demo? It'll help to reproduce the issue and get a solution.

  • ricardoventuraricardoventura Member ✭✭

    I have these on my MainActivity... I had to change it a little bit to work because the "boss" asked me to exit the app if the user revoked the permissions.

  • ricardoventuraricardoventura Member ✭✭

    @yelinzh,

    Dude, i'm crying. Very very thank you for your help. Finally I made it (you with, of course!).
    Have a great week!

    (Thank you again!)
    :heart:

  • JarvanJarvan Member, Xamarin Team Xamurai

    Congrats!

Sign In or Register to comment.