Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 91519 articles
Browse latest View live

Camera and gallery are not working in android, showing permission exception

$
0
0

Getting the following exception when loading the camera and gallery in my project.

Camera

Exception:>Plugin.Media.Abstractions.MediaPermissionException: Camera permission(s) are required. at Plugin.Media.MediaImplementation+d__17.MoveNext () [0x0009

Gallery

Does not have storage permission granted, requesting.01-02 15:16:08.566 I/mono-stdout(12958): Does not have storage permission granted, requesting. Storage permission Denied. 01-02 15:16:08.567 I/mono-stdout(12958): Storage permission Denied.[0:] Exception:>Plugin.Media.Abstractions.MediaPermissionException: Storage permission(s) are required. at Plugin.Media.MediaImplementation+d__16.MoveNext () [0x00091] in <5939e997f291496f805023da28f3a447>:0 --- End of stack trace from previous location where exception was thrown ---

I have added all the permissions in my manifest file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Added following codes in mainactivity:

[assembly: UsesFeature("android.hardware.camera", Required = false)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
 {
     PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
 }

Provider details in manifest file:

<provider android:name="android.support.v4.content.FileProvider" android:authorities="{packagename}.fileprovider" android:exported="false" android:grantUriPermissions="true">
    <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
</provider>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_images" path="Pictures" />
    <external-files-path name="my_movies" path="Movies" />
</paths>

Camera and Gallery codes:

public async void OpenMygallery()
    {
        try
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                ShowAlert("No photos available.");
                return;
            }

            _mediaFile = await CrossMedia.Current.PickPhotoAsync();

            if (_mediaFile == null)
                return;

            tweetPicture.Source = ImageSource.FromStream(() =>
            {
                return _mediaFile.GetStream();
            });
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
        }
    }

public async void OpenMyCamera()
    {
        try
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                ShowAlert("No camera available.");
                return;
            }

            _mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name = "test.jpg",
                AllowCropping = true
            });

            if (_mediaFile == null)
                return;

            tweetPicture.Source = ImageSource.FromStream(() =>
            {
                return _mediaFile.GetStreamWithImageRotatedForExternalStorage();
            });
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
        }
    }

Bug Information:

Version Number of Plugin: 4.0.1.5

Device Tested On: Redmi Note 5 Pro

Version of VS: 15.9.3

Version of Xamarin: 3.4.0.1008975

Anybody please suggest a solution for this?


My app command bar changed its color for no good reason

$
0
0

A strange thing happened to my application. The main window command bar (the one with minimize and maximize buttons) from common gray became black. The buttons stayed gray. I don't think I did anything to cause this.
Could you please give me any idea what did this and how to change this back?

How to Set Border Color for `Entry` tag in XAML.

$
0
0

Can we set or Change Border Color of Entry tag in XAML ?

Latitude and Longitude from Xamarin using IOS (Simulator or real device)

$
0
0

Hello There Guys,

Has anyone ever gotten longitude and latitude from an address in the iOS app successfully?

When i tried i kept getting this error

{Foundation.NSErrorException: Error Domain=kCLErrorDomain Code=8 "(null)"
at Xamarin.Essentials.Geocoding+d__4.MoveNext () [0x00075]

Funny it works in the android project.

I have used Xamarin Essentials and Xam.plugin.Geolocator, same error.

When i searched online it was said Apple does not recognise the address as a . valid one. If true, then whats the advisable solution since it works perfectly on android?

WOuld deeply appreciate your help

ListView ItemSelected and ItemTapped not working with ContextActions

$
0
0

Hi all.
I have a problem with ListView. I have a viewcell with custom control that has TapGestureRecognizer and it works well. But when I added Context Action to ViewCell ItemSelected stoped working.
What can I do to solve this problem?
Thanks for helping.

When does a file used to display an image in a ListView get released?

$
0
0

In our app, we draw a sketch using SkiaSharp. OnSave, the sketch is saved to a file and the commands used by SkiaSharp to draw the image are saved to SQLite. That way, at a later time, in a LoadView, we can have a list of sketches to chose from in a ListView.

The sketches are displayed via a path to the images like this:
<Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" Source="{Binding PhotoPath}" />

When an image is tapped that info is passed back to the SketchView where the details for creating the image are read from the table and displayed. If I make a small change (i.e. take very little time) and then save the Image over the previous version, sometimes I get the following exception:
Exception in SketchView.OnSaveButtonClicked: System.IO.IOException: The process cannot access the file <the file that I am trying to overwrite> because it is being used by another process.

It seems that if I spend more time adding to the sketch, or wait longer before tapping Save, that it is less likely to throw this exception.

I tried to only show the file name in the LoadView (i.e. no image). It is not a user friendly UI then, but it did not result in the Exception after around a dozen tries.

All that leads me to think that the LoadView hangs onto the images long after the View is closed. What can I do to free up that memory? What else should I consider?
Thanks!

Behaviors in ControlTemplates

$
0
0

I have a ControlTemplate defined in App.xaml for pages with ListViews like so:

<ControlTemplate x:Key="BaseModelListPageTemplate">
    <StackLayout>
        <Label
        Text="{TemplateBinding BindingContext.Category}"
        BackgroundColor="Green"
        TextColor="White"
        FontSize="24"
        FontAttributes="Bold"/>
        <ListView
            x:Name="ItemListView"
            HasUnevenRows="true"
            ItemsSource="{TemplateBinding BindingContext.ItemsList}"
            IsPullToRefreshEnabled="true"
            IsRefreshing="{TemplateBinding BindingContext.IsBusy, Mode=OneWay}"
            RefreshCommand="{TemplateBinding BindingContext.ReloadCommand}"
            ItemTemplate="{StaticResource BaseModelDataTemplateSelector}">
            <ListView.Behaviors>
                <Behaviors:ListViewScrollBehavior Command="{TemplateBinding BindingContext.LoadMoreCommand}"/>
            </ListView.Behaviors>
        </ListView>
    </StackLayout>
</ControlTemplate>

All bindings compile with no errors. The trouble is that an InvalidOperationException gets thrown: Operation is not valid due to the current state of the object. It worked fine when it was directly in a page and not in a ControlTemplate.

StackTrace is of little help:

at Xamarin.Forms.TemplateBinding+<Apply>d__17.MoveNext () [0x00018] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\TemplateBinding.cs:82 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (System.Object state) [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018 
  at UIKit.UIKitSynchronizationContext+<Post>c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIKitSynchronizationContext.cs:24 
  at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/Foundation/NSAction.cs:163 
  at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
  at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79 
  at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63 
  at EZDelivery.iOS.Application.Main (System.String[] args) [0x00008] in /Users/taylorartunian/Projects/EZDelivery/iOS/Main.cs:17 

Loading pins into map asynchronously

$
0
0

Is there a way to load pins without blocking the UI Thread? Would that be realistic for a great number of points?

I'm currently using amay's Google Maps library, and doing so isn't quite possible. While you can run the code on a different thread/with await and then call the method to actually add the pin in the main thread, doing so is a huge hit to performance.

Are there any libraries that support this? Is this doable if using custom renderers?

Ideally, end product would be a map that binds its pin source to an ObservableCollection to update it automatically in an asynchronous way (with the asynchronous part being the hard one), but that's another story.


Xamarin Forms - Android Lollipop java.lang.OutOfMemoryError problem

$
0
0

Hello,

When releasing my app in some Lollipop Devices I got some issues with OutOfMemoryError.

The error always happen in ListViews with images. In this case also CircleImages.

The error is:

java.lang.OutOfMemoryError: Failed to allocate a 18662412 byte allocation with 1643192 free bytes and 1604KB until OOM
    at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:741)
    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:562)
    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:590)
    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:620)

I have already research and tried a lot of solution but none succeed.

Solutions that I tried so far:

1 - From this topic, I tried to call GC.Collector(1) always when an image is compiled. I add a custom renderer like this:

[assembly: ExportRenderer(typeof(Image), typeof(ImageFixRenderer))]   

public class ImageFixRenderer : ImageRenderer
{
    public ImageFixRenderer()
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);
        GC.Collect(1);
    }

    protected override void Dispose (bool disposing)
    {
        try 
        {
            base.Dispose(disposing);
            GC.Collect(1);
        } 
        catch (Exception ex) 
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString ());
        }
    }
}

But it did not worked.

2 - From this topic , I tried to increase my Java Max Heap Size in Android Options, Advanced Tab to 1G.

But it did not worked also.

3 - From this topic, I tried to add android:largeHeap="true" in manifest file.

But not worked too.

Here is my custom CircleImageRender:

public class CircleImageRenderer : ImageFixRenderer
    {
        /// <summary>
        /// Used for registration with dependency service
        /// </summary>
        public static void Init() { }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);
            //GC.Collect(1);
            if (e.OldElement == null)
            {

                //Only enable hardware accelleration on lollipop
                if ((int)Android.OS.Build.VERSION.SdkInt < 21)
                {
                    SetLayerType(LayerType.Software, null);
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="child"></param>
        /// <param name="drawingTime"></param>
        /// <returns></returns>
        protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime)
        {
            try
            {
                var radius = Math.Min(Width, Height) / 2;
                var strokeWidth = 10;
                radius -= strokeWidth / 2;


                Path path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
                canvas.Save();
                canvas.ClipPath(path);

                var result = base.DrawChild(canvas, child, drawingTime);

                canvas.Restore();

                path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);

                var paint = new Paint();
                paint.AntiAlias = true;
                paint.StrokeWidth = ((CircleImage)Element).BorderThickness;
                paint.SetStyle(Paint.Style.Stroke);
                paint.Color = ((CircleImage)Element).BorderColor.ToAndroid();

                canvas.DrawPath(path, paint);

                paint.Dispose();
                path.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create circle image: " + ex);
            }

            return base.DrawChild(canvas, child, drawingTime);
        }
    }

Please I really need help on this. Anyone can give a hint?

Master Detail Page- keyboard issue.

$
0
0

I am using Menu in master detail page.
I am giving input to the entry, so that the keyboard appears. If I click the menu(on the top for Android & iOS, in the end for windows) button without clicking on detail page, the menu list appearing ,but the keyboard will not dismissing.

It is happening in all the three platforms. How to solve this.

VS 2017 xamarin sample - Hello, Android Multiscreen: Quickstart.

$
0
0

I am attempting to create the first Xamarin form. Using the sample HELLO, ANDROID MULTISSCREEN; QUICKSTART. I am at ADDING A LIST. Instruction Next, create an empty list that can be filled with phone numbers. The MainActivity class will look like this.
[Activity(Label = "Phoneword", MainLauncher = true)]
public class MainActivity : Activity
{
static readonly List phoneNumbers = new List();
...// OnCreate, etc.
}

Their is a copy sign but, there is not instruction as where to copy and place this code. All other code have instruction as where to paste the code. Please help.

How to pass Background Image from MainPage to object page from List View

$
0
0

Hello developers !

I'm begginer in xamarin and also in any programming language :wink: I'm just wondering how can i pass a background image to be displayed dependent on string i will pass from my list view where i displaying list of object , i'm storing in each object different background image as a string . I want to unify this becouse for purpose of my project i want to refer to just one page insted of 14. My goal is to have list of items and after clicking specific one , user moves to new page where see background image and text which is bind to object from model.
I tried to add this throught binding on Background Image property in my page.xaml code like but it's not working. :disappointed: :tired_face:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PersonApp.Views.PersonDetailPage"
             BackgroundImage="{x:Binding Person.Image}">

I don't know how to move on from this becouse at time when i'm writing i cannot figure it out how to pass parameter background image on new page :(

Do you have some tutorial i'm missing to do so ?
How should i pass Background image as binable parameter , should create this var as ImageSource type ?

Progress Bar only works if i use a Delay

$
0
0

Good Day

i am a Loading Page functionality that is defined here https://github.com/UdaraAlwis/Xamarin-Playground/tree/master/XFLoadingPageService . The loading Diaolog only show if i use

await Task.Delay(2000);

my code looks like this

 private async void btnstart_Clicked(object sender, EventArgs e)
        {
            DependencyService.Get<ILodingPageService>().InitLoadingPage(new LoadingIndicatorPage2());
            DependencyService.Get<ILodingPageService>().ShowLoadingPage();

            data .data obj = new data .data ();
            try
            {
                lblstatus.Text = "Before the call";
                // just to showcase a delay...
               // await Task.Delay(2000);

                    var lstentities = await obj.FindPerson_Report_Basic("81248877");

                lblstatus.Text = "After the call";
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error:", ex.Message, "Ok");
            }
            finally
            {
                obj = null;
                DependencyService.Get<ILodingPageService>().HideLoadingPage();
            }
        }

but the loading page does not load , as you can see i commented the Delay part.

Thanks

Xamarin.Forms CardsView nuget package

$
0
0

Hi all) I've released new package for Xamarin.Forms (Something like Tinder's CardsView)
Maybe, someone will be interested in it

nuget.org/packages/CardsView/ -- nuget
github.com/AndreiMisiukevich/CardView -- source and samples

CarouselView implementation, CardsView nuget package


ListView not working in CarouselView

$
0
0

Greetings!

I am trying to include a ListView as an element in a static array in a CarouselView. This is the XAML code in my sandbox project:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinSandbox"
             xmlns:cv="clr-namespace:CarouselView.FormsPlugin.Abstractions;assembly=CarouselView.FormsPlugin.Abstractions"
             x:Class="XamarinSandbox.MainPage">

    <cv:CarouselViewControl x:Name="carousel" 
                            InterPageSpacing="10"
                            Orientation="Horizontal"
                            Position="{Binding Position}"
                            ShowArrows="True"
                            ShowIndicators="True"
                            HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <cv:CarouselViewControl.ItemsSource>
            <x:Array Type="{x:Type View}">

                <Label Text="{Binding LabelText}" BackgroundColor="CadetBlue" FontSize="Large"
                       HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />

                <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Label Text="{Binding ProgramModeInstructionsText}" FontSize="Large"
                           HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />

                    <ListView ItemsSource="{Binding ItemsSource}" SelectedItem="{Binding SelectedItem}"
                              HasUnevenRows="True" HeightRequest="200" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                               <TextCell Text="REMOVE THIS LINE AND THE CODE COMPILES" />
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                    <Label Text="{Binding SelectedProgramModeDescription}" FontSize="Large"
                           HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />
                </StackLayout>

            </x:Array>
        </cv:CarouselViewControl.ItemsSource>

    </cv:CarouselViewControl>

</ContentPage>

With this XAML definition, I receive the following compilation error: Value cannot be null. Parameter name: fieldType
(I am using [assembly: XamlCompilation(XamlCompilationOptions.Compile)])

I have been removing lines and compiling to see where the error lays.
If I remove the TextCell element, then the XAML definition compiles without error.

I am at a loss to understand what is going on. This is a basic sandbox project with nothing else in it save the view model that responds to this view. However, I have removed every binding to make the example as simple as possible. The code behind class has had no code added to it.

Does anyone have any ideas why this is not compiling?
Using Xamarin version 2.5.0.280555.
Thank you.

Xamarin.CardIO documentation or examples.

$
0
0

Hello. A want scan debit/credit card data (card number, holder name etc.) using smartphone camera. I found Xamarin.CardIO.iOS and Xamarin.CardIO.Android libraries, but there are no any documentation or examples how to use it. In the end I want to create some Xamarin Forms control for using it from XAML. But now I need any documentation or examples. Could someone help me?

How to get the length in seconds of a WAV file?

$
0
0

Hi guys, I have been trying to find out how to get the length of a wave file recording for both Android and iOS.
Can it be done in the PCL, or there are specific platform methods to get this length?

HotReload LiveReload LiveXaml [Mac] [Windows] [nuget package] [opensource]

Hamburger icon iOS (Xamarin.Forms)

$
0
0

I followed this wonderful blog post and my hamburger menu works great... on Android. The icon appears, and it is even animated.

On iOS I don't get the hamburger. I have put a hamburger icon into the toolbar, but of course it sits in the middle, not where it belongs (on the far left, where the back arrow would otherwise be).

Any ideas on how I can get this icon to work?

Thanks!!

Viewing all 91519 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>