Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Xam.Plugin.Media after camera capture app crashes without any error

RAJESHGANAPATHYRAJESHGANAPATHY USMember ✭✭
edited June 2020 in Xamarin.Forms

Hello,

I am using Xam.Plugin.Media in my xamarin forms (Xamarin.Forms 4.5.0.530) mobile app. App gets crashed after camera capture strangely without any error. Camera captured image also gets stored in the desired folder I set. I don't know how to proceed further, would appreciate if someone could help me move forward.

Code snippet and other App details are attached below:

Shared Project

XAML

<ContentPage.Resources>
            < ResourceDictionary>
                < services:Null2StringConverter x:Key="Null2String"/>
                < services:ByteToImageFieldConverter x:Key="ByteArrayToImage"/>
            < /ResourceDictionary>
    </ContentPage.Resources>

    <Grid ColumnSpacing="16">
        <StackLayout Grid.Column="0">
            <Image
                x:Name="PhotoImage"
                Aspect="AspectFit"
                Source="{Binding PhotoByte, Converter={StaticResource ByteArrayToImage}, Mode=TwoWay}" />
        </StackLayout>
        <StackLayout  Grid.Column="1">
            <Button Grid.Column="1" WidthRequest="200"
                x:Name= "btnTake"
                Text = "Take Picture"
                Style="{StaticResource ButtonBlueWhite}"
                HorizontalOptions = "End"/>
        </StackLayout>
    </Grid>

View

    public partial class PODUpdate : ContentPage
    {
            PODViewModel viewModel;

                public PODUpdate()
                {   
                     InitializeComponent();

                        BindingContext = viewModel = new PODViewModel(2);
                }



                private void BtnTake_Clicked(object sender, EventArgs e)
                {
                    PictureClick();
                }


                private async void PictureClick()
                {
                    try
                    {
                        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                        {
                            await DisplayAlert("No Camera", ":( No camera available.", "OK");
                            return;
                        }

                        string mFileName = DateTime.Now.Year.ToString() +
                                            DateTime.Now.Month.ToString() +
                                            DateTime.Now.Day.ToString() +
                                            DateTime.Now.Hour.ToString() +
                                            DateTime.Now.Minute.ToString() +
                                            DateTime.Now.Second.ToString();


                        await CrossMedia.Current.Initialize();

                        var photo = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                        {
                            MaxWidthHeight = 2500,
                            CompressionQuality = 80,
                            DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Front,
                            Name = mFileName,
                            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small
                        });

                        if (photo == null)
                            return;


                        if (photo != null)
                        {
                            viewModel.IsPhotoTaken = true;
                            viewModel.PhotoByte = System.IO.File.ReadAllBytes(photo.Path);

                            photo.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert(this.Title, ex.Message+ ex.InnerException, "Ok");
                        return;
                    }
                }
    }

Android Project
AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.Flyking.ibots.netmobile" android:installLocation="auto">
        <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
        <application android:label="Ibots.NetMobile.Android" android:icon="@drawable/FlykingIcon">
            <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.Flyking.ibots.netmobile.fileprovider" android:exported="false" 
                  android:largeHeap="true" android:grantUriPermissions="true">
                <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
            </provider>
        </application>
      <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.FLASHLIGHT" />
    </manifest>

AssemblyInfo.cs

    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using Android.App;

    // General Information about an assembly is controlled through the following 
    // set of attributes. Change these attribute values to modify the information
    // associated with an assembly.
    [assembly: AssemblyTitle("Ibots.NetMobile.Android")]
    [assembly: AssemblyDescription("")]
    [assembly: AssemblyConfiguration("")]
    [assembly: AssemblyCompany("")]
    [assembly: AssemblyProduct("Ibots.NetMobile.Android")]
    [assembly: AssemblyCopyright("Copyright ©  2014")]
    [assembly: AssemblyTrademark("")]
    [assembly: AssemblyCulture("")]
    [assembly: ComVisible(false)]

    // Version information for an assembly consists of the following four values:
    //
    //      Major Version
    //      Minor Version 
    //      Build Number
    //      Revision
    //
    // You can specify all the values or you can default the Build and Revision Numbers 
    // by using the '*' as shown below:
    // [assembly: AssemblyVersion("1.0.*")]
    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyFileVersion("1.0.0.0")]

    // Add some common permissions, these can be removed if not needed
    [assembly: UsesPermission(Android.Manifest.Permission.Internet)]
    [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
    #if DEBUG
        [assembly: Application(Debuggable = true, UsesCleartextTraffic = true)]
    #else
        [assembly: Application(Debuggable = false, UsesCleartextTraffic = true)]
    #endif

    [assembly: UsesPermission(Android.Manifest.Permission.Camera)]
    [assembly: UsesFeature("android.hardware.camera", Required = true)]
    [assembly: UsesFeature("android.hardware.camera.autofocus", Required = true)]

MainActivity.cs

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {

            protected override void OnCreate(Bundle savedInstanceState)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;

                base.OnCreate(savedInstanceState);
                Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);

                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

                ZXing.Net.Mobile.Forms.Android.Platform.Init();

                LoadApplication(new App());
            }



            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
            {
                global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);

                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }

    }

Thanks - G Rajesh

Best Answer

  • RAJESHGANAPATHYRAJESHGANAPATHY USMember ✭✭
    Accepted Answer

    Thanks again LeonLu. Appreciate it.

    Finally I figured out what the real problem was:

    In the android project, MainActivity.cs
    [Activity(Theme = "@style/MyTheme.Splash", MainLauncher = true, NoHistory = true]

    Basically After removing Nohistory attribute, the app didn't crash post image capture.

    Thanks again

    G Rajesh

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    I test this plugin with Xamarin.Forms 4.5.0.530, other nuget packages verson like following screenshot.

    Here is running gif.

    Here is my demo, you can download my demo, then run it in your device, if it could running normally.

  • RAJESHGANAPATHYRAJESHGANAPATHY USMember ✭✭

    Thanks LeonLu.

    However, I tried your code to adapt in my project and the application still crashes. Even my earlier code if i try on a brand new project, it works.

    Is there any project level setting which is bothering ?

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    You can try to update your nuget package to latest version, then delete bin and obj folders, rebuild your project, if this issue will disappear.

  • RAJESHGANAPATHYRAJESHGANAPATHY USMember ✭✭
    Accepted Answer

    Thanks again LeonLu. Appreciate it.

    Finally I figured out what the real problem was:

    In the android project, MainActivity.cs
    [Activity(Theme = "@style/MyTheme.Splash", MainLauncher = true, NoHistory = true]

    Basically After removing Nohistory attribute, the app didn't crash post image capture.

    Thanks again

    G Rajesh

Sign In or Register to comment.