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

Firebase Analytics : The call is ambiguous between the following methods or properties

$
0
0

Hi,

Why I keep getting this error in my Xamarin Forms iOS project and how to fix it please?

The call is ambiguous between the following methods or properties: 'Analytics.LogEvent(string, NSDictionary<NSString, NSObject>)' and 'Analytics.LogEvent(string, Dictionary<object, object>)'

for this code [on line Analytics..LogEvent(eventId, null);]

using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Text;
using Firebase.Analytics;
using Firebase.Core;
using Foundation;
using Jafaria;
using Jafaria.iOS;

[assembly: Xamarin.Forms.Dependency(typeof(GoogleFirebaseAnalytics))]
namespace Jafaria.iOS
{
    public class GoogleFirebaseAnalytics : IFirebaseAnalytics
    {

        public void FirebaseLogEvent(string eventId)
        {
            LogEvent(eventId, (IDictionary<string, string>)null);
        }

        /*
        public void LogEvent(string eventId, string paramName, string value)
        {
            LogEvent(eventId, new Dictionary<string, string>
            {
                { paramName, value }
            });
        }
        */

        public void LogEvent(string eventId, IDictionary<string, string> parameters)
        {
            if (parameters == null)
            {
                Analytics..LogEvent(eventId, null);
                return;
            }

            var keys = new List<NSString>();
            var values = new List<NSString>();
            foreach (var item in parameters)
            {
                keys.Add(new NSString(item.Key));
                values.Add(new NSString(item.Value));
            }

            var parametersDictionary =
                NSDictionary<NSString, NSObject>.FromObjectsAndKeys(values.ToArray(), keys.ToArray(), keys.Count);
            Analytics.LogEvent(eventId, parametersDictionary);

        }
    }
}

JSON Date value as null, how to check if it is null or not?

$
0
0

Hi everyone, first of all thank you in advance for all the help. I am new at Xamarin Forms and trying to do the following:

I am calling an API, which returns a JSON string that includes a DATE value, but sometimes this value can be null, so my question is how to check is the value is Null?

I am trying to populate a myDate.Date from CodeBehind to update data, but since this value is null, it gives me an error saying that DateTime can't convert null to date.

Here is the Exception:

Newtonsoft.Json.JsonSerializationException
Error converting value {null} to type 'System.DateTime'. Path 'myDate', line 16, position 20.

Please help, thanks

Focusing on Entry Field Each Time a ContentView View Shows

$
0
0

I have MyView.xaml.cs and MyView.xaml (which is a ContentView) defining MyView view.

MyView has an Entry field. How do I focus on that Entry field each time MyView is shown on screen?

Originally, I thought I could just to to MyView.xaml.cs and override OnAppearing() lifecycle method. But ContentView does not have OnAppearing().

Where do I find my 'App Bundle' file for nUnit testing

$
0
0

Can't seem to find the file location designated for the App Bundle when configuring nUnit testing project in my xamarin forms app

        app = ConfigureApp
                        .iOS
                        .AppBundle("/????)
                        .StartApp();

Single Xaml entry to detect Phone number/Email id on entering the text

$
0
0

Hello Guys,

I'm developing a payment portal where the user has to confirm either phone number or email id to process the Payment. So, I'm planning to have single entry control which detects phone number/email id upon entering the text instead of having two separate entries to confirm phone number and email id.

Did anyone come across such situation?

Please suggest.

Not able to bind data to other controls execpt picker in listview

$
0
0

Hi All,

I am trying to bind data to listview but able to bind only for picker control in listview other controls are getting null. Please suggest me answers to get values

Class file

public class ClsRenWeekly
    {
        public string strdates { get; set; }
        public int strdateid { get; set; }
    }

    public class ListItemModel
    {
        public string Strbtnno { get; set; }
        public bool blnrenew { get; set; }
        public string strsttartper { get; set; }
        public string strendper { get; set; }
        public string strrent { get; set; }
        public List<ClsRenWeekly> ClsRenWeekly { set; get; }
    }

Xaml page

 <StackLayout>
        <ListView x:Name="lstrenewal" Margin="0,20,0,0" IsVisible="True"    HasUnevenRows="True"  ItemTapped="lstrenewal_ItemTapped" VerticalOptions="FillAndExpand"  >

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                        <Grid Margin="0,0,0,0"  HorizontalOptions="CenterAndExpand"  BackgroundColor="#3150af"  >

                            <Grid.RowDefinitions >
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20*" />
                                <ColumnDefinition Width="20*" />
                                <ColumnDefinition Width="20*" />
                                <ColumnDefinition Width="20*" />
                                <ColumnDefinition Width="20*" />
                            </Grid.ColumnDefinitions>

                            <Label x:Name="lblboothno" Text="{Binding Strbtnno}" Margin="0,5,0,5" Grid.Row="0" XAlign="Center" Grid.Column="0" HorizontalOptions="CenterAndExpand"   FontSize="18" FontAttributes="Bold" TextColor="White" />
                            <control:CheckBox x:Name="chkrenweekly" Checked="{Binding blnrenew}"
                                        HorizontalOptions="CenterAndExpand" BackgroundColor="White"
                                        TextColor="#348e8a" Margin="20,0,0,0" Grid.Row="0" Grid.Column="1"  />
                            <Label x:Name="lblstrper" Text="{Binding strdatestart}"  Margin="0,5,0,5" Grid.Row="0" XAlign="Center" Grid.Column="2" HorizontalOptions="CenterAndExpand"   FontSize="18" FontAttributes="Bold" TextColor="White" />
                            <Picker x:Name="pckdate" ItemsSource="{Binding ClsRenWeekly}" TextColor="Red" Grid.Row="0" Grid.Column="3"    ItemDisplayBinding="{Binding strdates}"
                                    Title="Choose date" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
                            <Label x:Name="lblrent" Text="{Binding strrent}"  Margin="0,5,0,5" Grid.Row="0" Grid.Column="4"  XAlign="Center" HorizontalOptions="CenterAndExpand"  FontSize="18" FontAttributes="Bold" TextColor="White" />

                        </Grid>

                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Xaml cs page

List<ListItemModel> list = new List<ListItemModel>();

            var model = new ListItemModel();
            {
                new ListItemModel() { Strbtnno = "A1", strsttartper = "March", blnrenew = true, strrent = "50" };
            }

            model.ClsRenWeekly = new List<ClsRenWeekly>()
            {
                new ClsRenWeekly() { strdates = "March" },

                new ClsRenWeekly() { strdates = "April" }

            };
            list.Add(model);
            lstrenewal.ItemsSource = list;

ListView - jump list without group headers

$
0
0

Hello,

We want a jump list on our list view, but no group headers. Is there any way this is possible? I am using grouping to get the jump list, but can't figure out how to hide / suppress the group headers. I have tried setting the binding to "." and alternately tried creating an empty view with height zero for the group header template, but it still displays a ~25 height empty gray row. Any way to get one without the other?

How to change TabbedPage items text color on Xamarin.Forms android?

$
0
0

Hello, does anyone know how I can change the text color of the "TabbedPage" items?
As you can see in screenshot, the current color does not fit the background and makes the items "unreadable".


Custom button BackgroundColor not updating

$
0
0

Hey there!

I'm currently facing a problem trying to update the color of a CustomButton I've made when it's clicked. Have been searching the forums/internet in general for a solution, but no luck yet. Being new to Xamarin Forms, I'm quite unsure of the way I've been doing things, and assume I'm missing something to make it work.

Anyway: I need a different button for each item of a table in my database. To achieve this dynamic creation, I've resorted to creating the custombuttons in code-behind instead of Xaml. Only the color of the clicked button has to change, so to bind the BackgroundColorProperty I'd need a different property for each one in my ViewModel; and, as the number of buttons is dynamic, I don't see a way of doing that.

So I created a command (using Prism) that receives the clicked button as a parameter (which isn't exactly right as far as MVVM goes, I guess) to change just its BackgroundColor. Thing is, it doesn't work if the BackgroundColor has already been set. If it hasn't it works fine, though until the user clicks the button its background is transparent (hasn't been set).

I've only tested with Android so far, but I assume it's a problem with the custom renderer? As in the CustomRenderer might not be getting the event(?) to redraw the background. But if this is the case, why would it work if the color isn't set yet?

Might be obvious, but I'm still quite new to Xamarin Forms, and I fear my limited experience won't be enough to solve this, as I've been trying for longer than I'd like to admit already.

Custom button code:

   public class CustomResidueButton : Button
                    {

                        public static readonly BindableProperty CustomTextProperty =
                            BindableProperty.Create("CustomText", typeof(string), typeof(CustomResidueButton), string.Empty);

                        public string CustomText
                        {
                            get { return (string)GetValue(CustomTextProperty); }
                            set { SetValue(CustomTextProperty, value); }
                        }


                        public static readonly BindableProperty CustomImageProperty =
                            BindableProperty.Create("CustomImage", typeof(string), typeof(CustomResidueButton), string.Empty);

                        public string CustomImage
                        {
                            get { return (string)GetValue(CustomImageProperty); }
                            set { SetValue(CustomImageProperty, value); }
                        }

                        public static readonly BindableProperty ResidueIdProperty =
                            BindableProperty.Create("ResidueId", typeof(string), typeof(CustomResidueButton), string.Empty);

                        public string ResidueId
                        {
                            get { return (string)GetValue(ResidueIdProperty); }
                            set { SetValue(ResidueIdProperty, value); }
                        }

                    }

Custom buttons creation in the main-page's code behind, called on the constructor:

private void CreateAndLoadResidueButtons(Grid filterGrid)
            {
                if (APIUtil.ResidueList != null)
                {
                    int row = 1;
                    int column = 0;

                    foreach (Residue residue in APIUtil.ResidueList)
                    {
                        CustomResidueButton btn = new CustomResidueButton
                        {
                            //Style = residueBtnStyle,
                            CustomText = residue.residueName,
                            CustomImage = "tire",
                            ResidueId = residue.residueId.ToString(),

                            Command = ((MainMapViewModel)BindingContext).ResidueSelectedCommand,
                        };

                        Thickness margin = new Thickness();

                        if (row == 3)
                            margin.Bottom = 6;
                        if (column == 0)
                            margin.Left = 6;
                        if (column == 2)
                            margin.Right = 6;

                        btn.Margin = margin;

                        btn.CommandParameter = btn;

                        filterGrid.Children.Add(btn, column, row);

                        if (column == 2)
                        {
                            column = 0;
                            row++;
                        }
                        else
                            column++;
                    }
                }
            }

Command for when a button is clicked:

    public DelegateCommand<object> ResidueSelectedCommand { get; set; }
            private void CreateCommands()
            {
                ResidueSelectedCommand = new DelegateCommand<object>(ResidueSelectedExecute);
            }

            private void ResidueSelectedExecute(object selectedButton)
            {
                if (CanClick)
                {
                    CanClick = false;

                    MessagingCenter.Send(new MessageService(), "ChangedResidueType");

                    CustomResidueButton btn = selectedButton as CustomResidueButton;
                    int resId = int.Parse(btn.ResidueId);

                    if (SelectedResidueIdList.Any(i => i == resId))
                    {
                        SelectedResidueIdList.Remove(resId);
                        btn.BackgroundColor = Color.Pink;

                    } else {
                        SelectedResidueIdList.Add(resId);
                        btn.BackgroundColor = Color.Yellow;
                    }

                    if (SelectedResidueIdList.Count > 0)
                        LoadPins(APIUtil.GetSitesOfResidueList(SelectedResidueIdList));
                    else
                        LoadPins(APIUtil.GetAllSites());

                    CanClick = true;
                }
            }

And finally, the Android custom renderer:

class ResidueButtonRenderer : ViewRenderer<CustomResidueButton, Android.Views.View>
        {
            private readonly Context _context;

            public ResidueButtonRenderer(Context context) : base(context)
            {
                _context = context;
            }

            private TextView _residueNameView;
            private ImageView _residueIconView;

            protected override void OnElementChanged(ElementChangedEventArgs<CustomResidueButton> e)
            {
                base.OnElementChanged(e);

                //e.NewElement.CommandParameter = Element.CommandParameter;

                if (Control == null)
                {
                    // Element é o CustomResidueButton
                    // inflate no layout do botão
                    var inflater = _context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
                    var rootLayout = inflater.Inflate(Resource.Layout.ResidueButton, null, false);

                    _residueNameView = rootLayout.FindViewById(Resource.Id.ResidueName) as TextView;
                    _residueNameView.Text = Element.CustomText;

                    // usa a string do CustomResidueButton de nome pra pegar imagem do drawable
                    int imageId = Context.Resources.GetIdentifier(Element.CustomImage, "drawable", Context.PackageName);
                    _residueIconView = rootLayout.FindViewById(Resource.Id.ResidueIcon) as ImageView;
                    _residueIconView.SetImageResource(imageId);

                    SetBackground(rootLayout);
                    SetNativeControl(rootLayout);

                    // executa os Commands, o conteudo de Execute() é o CommandParameter
                    rootLayout.Click += (s, a) => Element.Command?.Execute(Element.CommandParameter);
                }
            }

            private void SetBackground(Android.Views.View rootLayout)
            {
                var backgroundColor = Element.BackgroundColor.ToAndroid();

                var enabledBackground = new GradientDrawable(GradientDrawable.Orientation.LeftRight, new int[] { backgroundColor, backgroundColor });
                var stateList = new StateListDrawable();
                var rippleItem = new RippleDrawable(ColorStateList.ValueOf(Android.Graphics.Color.White), enabledBackground, null);

                stateList.AddState(new[] { Android.Resource.Attribute.StateEnabled }, rippleItem);

                rootLayout.Background = stateList;
            }

        }

At this point any kind of help would be appreciated, even if it's just telling me I'm doing things completely wrong. :tongue:
Thanks in advance!

Problem to update ListView whit ObservableCollection

$
0
0

Well First than nothing, i don't speak english, sorry if i write anything wrong.

My probles is the next, i working with Websocket, my server send to my app a list of Json, that is fine, but my problem is when i try show this list of json y my ListView across of my ObservableCollection, if i initialize all in the constructor of my ViewModel before, the View show the items rigth, but when i try to update that lisview whit the data of the Json, this don't update, here is my code:

This is the MODEL, to receive the correct format of the JSON

       public class datosJson : INotifyPropertyChanged{
            #region VARIABLES
            private String _id;
            private String _nombre;
            private String _descripcion;
            #endregion

            #region PROPIEDADES
            public string Id { get => _id;
                set {
                    _id = value;
                    OnPropertyChanged();
                }
            }
            public string Nombre { get => _nombre;
                set {
                    _nombre = value;
                    OnPropertyChanged();
                }
            }
            public string Descripcion { get => _descripcion;
                set {
                    _descripcion = value;
                    OnPropertyChanged();
                }
            }
            #endregion

            #region INotityPropertyChanged
            public event PropertyChangedEventHandler PropertyChanged;

            void OnPropertyChanged([CallerMemberName] string propertyName = null){
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            #endregion
}

This is my View with my ListView component, 'Datos' is my ObservableCollections and 'Nombre' 'Descripcion' the fields than i want show:~~~~

        <ListView ItemsSource="{Binding Datos}"
                  Header="JSON"
                  Footer="Fin del listado">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding Nombre}"/>
                            <Label Text="{Binding Descripcion}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

This is my ViewModel:

      class ChatPageViewModel : INotifyPropertyChanged {
     List<datosJson> orders = new List<datosJson>();
         public ObservableCollection<datosJson> Datos { get; set; }

      #region CONSTRUCTOR
          public ChatPageViewModel() {
          Datos = new ObservableCollection<datosJson>(orders);
          }

      #region METODOS
          public async void ConnectToServerAsync() {
      <CodeToConnectWithServer>
       ...
       orders = JsonConvert.DeserializeObject<List<datosJson>>(serialisedMessage);

           //HERE IS MY PROBLEM                      
           Datos = new ObservableCollection<datosJson>(orders.ToList());

           //SEE IF THE DATA IS COMING RIGTH
           for(int i = 0; i < Datos.Count; i++){
                      Console.WriteLine("-MENSAGE:- " + orders[i].Nombre);
           }
       }
       #endregion

I don't knows why the listview don't update if i set the data in my ObservableCollection..

PLEASE HELP ME :(

Best way to iterate through a selection of Xamarin.Forms controls?

$
0
0

Does anyone know a better way to loop through the children of than this:

        void OnSliderValueChanged(object sender, ValueChangedEventArgs args)
        {
            double value = args.NewValue;
            foreach (Label label in A.Children)
            {
                label.HeightRequest = value;
                label.WidthRequest = (value * 4);
                label.FontSize = value;
            }
        }

Can I assign controls to a "class" as in HTML and then iterate through the class members?
Can I refer to the children without specifying their type and just iterate by ordinal position, as in A.Children(5).HeightRequest = value; ?

Is nested navigation in the Master view of a MasterDetail possible?

$
0
0

I am trying to create an Android tablet and phone app with a side pane on the tablet version with full hierarchical navigation. It should be a menu with sub-menus, and selecting a child in the sub menu sends a page to the Detail view. The phone version should have this menu and it's children as the full screen, and the detail screen becomes the full screen.

I am aware that ListViews can be embedded in a Master view, and that grouping is available. However I'm hoping to have a fully hierarchical navigation like you might find in, say, a settings module of an app, but in the master side of a Master Detail.

Is a Master Detail the right way to go about this? If not, I think I'm going to have use the ListView with navigation on the first 3rd of the screen in tablet mode, and just have this view fill the entire screen on the mobile version. My biggest concern is handling the navigation stack.

I have tried Googling my requirement but so far haven't found anything quite like what I'm trying to do.

I would be grateful for anyone's experience of a similar problem. A code sample would be even better.

Binding between elements

$
0
0

In terms of best practises, what is the best way for interacting among elements through data binding. Is it setting a x:Name for the source and do a typical data binding. Or it's better to have the source send it's value to the view model using OneWayToSource binding mode and then the target retrieve it from the view model

Question about Xamarin Essentials’s GetLastKnownLocationAsync

$
0
0

Hi,

@JamesMontemagno I have a question about Xamarin Essentials’s GetLastKnownLocationAsync

I didn’t find more details about it on the docs

For example, when to check for it? and when will it empty? how does it work? will it change every time you connect to the app or every time you start gps or it will only change when you move within 3k (low accuracy)?

oh one more thing, why the forum does not have a tag for Xamarin Essentials when you create a new question? o:) B)

Thanks,
Jassim

Xamarin Android web view blinks/show black while rendering and some times crashes the App

$
0
0

I am working in xamarin forms with androrid native web view. We have to load the external site (used for our project only) with signature pad in it to get signature from our end user and i had came across few issues in Android phone (all the devices, most occurred in MOTO G5) below, these issues occurs after continuous usage of web view about 45 min to 1 hr.
1. While web view starts rendering the site, the page blinks with black.
2. Some times first half of page was loaded with black screen and remaining half was fine.
3. Some times app crashed on tapping the signature pad inside the site.

The external site has compiled with css styles ,images and javascript written by our external vendor (Kind of receipt page). We had to load many receipts site to sign all of it. All the receipt site base URL was same and has a unique URL for each receipt.

We have created the WP8.1 application few years back with windows web view and it all working fine till now with no issues. Now we are trying to upgrade the same application to all platform (Android , iOS and Windows) using Xamarin forms.

i had tried with the custom renderers for the forms web view and tried rendering the native android web view in xamarin forms page. And even tried with destroying/disposing the web view. But still the issue occurs.

My Project Info,
Xamarin.Forms.2.5.0.77107.
Application target version for android 7.1 (min support version 6.0)
Mono android version 7.1

Has anyone came across this issue? Please help me on this.


How to integrate apply pay and Google pay in Xamarin Forms

$
0
0

Is there any way to implement apply pay in xamarin forms application. I know it can be done by dependency injection but if anyone has code then please share...

Trigger Change inside ObservableCollection

$
0
0

Hello Everyone

I have ObservableCollection of an object e.g ObservableCollection, inside user I have an object e.g Car and a bool property. The collection is bound to a listview and I would like to update listview when a a property of Car changes.

I did some google searching and tried few solutions but did not work.

Any suggestion would be appreciated.

Thanks

app is terminated after launching(xamarin.ios)app

$
0
0

app is terminated after launching(xamarin.ios)app
Launch failed. The app 'App1.iOS' could not be launched on 'iPhone'. Error: error MT1007: Failed to launch the application '/Users/dsgs/Library/Caches/Xamarin/mtbs/builds/App1.iOS/ab70f97c9774c4c76b94c0296ebef022/bin/iPhone/Debug/App1.iOS.app' on the device 'iPhone': Failed to launch the application 'com.yourcompany.App1' on the device 'iPhone': Invalid Service Error (error: 0xe8000022). You can still launch the application manually by tapping on it.

XAML Previewer for Xamarin.Forms not working on VS2017

Paypal.Forms Xamarin cannot serialize PaymentResult

$
0
0

Using

  • Xamarin Forms
  • VS 2017
  • Paypal.Forms 2.18.3 from @AlejandroRuiz
    *Linker Behavior => "Link All"

When I try to receive a PaymentResult I get the next error:

Unhandled Exception:

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type PayPal.Forms.Abstractions.PaymentResult+PayPalPaymentResponse.
A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.
Path 'client', line 2, position 12. occurred

I had a similar problem with local classes and I fixed adding the attribute [Preserve] or [Preserve(AllMembers=true)] before the class
or [JsonConstructor] before the constructor.

But in this case, PayPal.Forms.Abstractions.PaymentResult is an external referenced class. I don´t know how to add this attributes of use any other solution.

This is a part of my code when I get the error:

            PayPalItem charge = new PayPalItem("Recarga de saldo", decimal.Parse(Amount), "MXN");
                        PaymentResult ResultPayment = await CrossPayPalManager.Current.Buy(charge, new Decimal(0)); //In this line I get the error
                        if (ResultPayment.Status == PayPalStatus.Cancelled)
                        {
                            //ShowAlert("Cancelled", result.ErrorMessage);
                        }
                        else 
            if (ResultPayment.Status == PayPalStatus.Error)
                        {
                            ShowAlert("Error", ResultPayment.ErrorMessage);
                        } 
            else 
            if (ResultPayment.Status == PayPalStatus.Successful)
                        {
                            bool rechargeOK = await SendRecharge(ResultPayment.ServerResponse.Response.Id);
                            if (rechargeOK)
                            {
                                ....//ComplementaryCode
                            }                          
                        }

On Android with Linker => "None" I dont have this issue.
If I don´t use Linker => "Link All" on iOS I have more errors only with Link All my project works.
I hope you can help me.

I attach the image with the error.


Viewing all 91519 articles
Browse latest View live


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