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

ContentView bindings not working

$
0
0

Hi everyone, I'm trying to create a custom control that allows me to show an horizontal list after having loaded the data from an online resource.
I'm still new to creating custom controls with property binding and this is quite frustrating to be honest :# .

In order to do what I want I derived a ContentView and this are its XAML an code-behind:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:ff="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
    x:Class="AppName.Controls.BrandsCarousel"
    x:Name="brands_carousel"
    HeightRequest="120">
    <ContentView.Content>
        <StackLayout BindingContext="{x:Reference brands_carousel}">
            <ActivityIndicator IsVisible="{Binding IsLoading}" IsRunning="{Binding IsLoading}" />
            <CollectionView IsVisible="{Binding IsNotLoading}" ItemsSource="{Binding Brands}">
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Horizontal" Span="1" HorizontalItemSpacing="8" />
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <ff:CachedImage LoadingPlaceholder="tab_home" Source="{Binding Image}" WidthRequest="150" Aspect="AspectFit" />
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
    </ContentView.Content>
</ContentView>


using System.Collections;
using System.Runtime.CompilerServices;
using Xamarin.Forms;

namespace AppName.Controls
{
    public partial class BrandsCarousel : ContentView
    {
        public static readonly BindableProperty BrandsProperty =
            BindableProperty.Create(nameof(Brands), typeof(IEnumerable), typeof(BrandsCarousel), null,
                                    propertyChanged: OnBrandsChanged, defaultBindingMode: BindingMode.OneWay);

        public static readonly BindableProperty IsLoadingProperty =
            BindableProperty.Create(nameof(IsLoading), typeof(bool), typeof(BrandsCarousel), null,
                                    propertyChanged: OnIsLoadingChanged, defaultBindingMode: BindingMode.OneWay);

        private static void OnBrandsChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (BrandsCarousel)bindable;
            control.Brands = newValue as IEnumerable;
        }

        private static void OnIsLoadingChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (BrandsCarousel)bindable;
            control.IsLoading = (bool)newValue;
        }

        public IEnumerable Brands
        {
            get => (IEnumerable)GetValue(BrandsProperty);
            set => SetValue(BrandsProperty, value);
        }

        public bool IsLoading
        {
            get => (bool)GetValue(IsLoadingProperty);
            set
            {
                SetValue(IsLoadingProperty, value);
                OnPropertyChanged(nameof(IsNotLoading));
            }
        }

        public bool IsNotLoading
        {
            get => !(bool)GetValue(IsLoadingProperty);
        }

        public BrandsCarousel()
        {
            InitializeComponent();
        }
    }
}

This is the view in which I'm including the custom control:

<?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:ff="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
    xmlns:controls="clr-namespace:AppName.Controls"
    xmlns:vm="clr-namespace:AppName.ViewModels"
    x:Class="AppName.Views.HomePage"
    Title="Home">
    <ContentPage.BindingContext>
        <vm:HomeViewModel />
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout Spacing="0">
            <Label Text="Our brands" StyleClass="SectionTitleLabel" />
            <controls:BrandsCarousel Brands="{Binding Brands}" IsLoading="{Binding LoadingBrands}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>


using Xamarin.Forms;

namespace AppName.Views
{
    public partial class HomePage : ContentPage
    {
        public HomePage()
        {
            InitializeComponent();
        }
    }
}

And this is the view model associated with the view, responsible of loading the data from the online resource

using System.Collections.ObjectModel;
using System.Threading.Tasks;
using AppName.Models;
using AppName.Services;
using AsyncAwaitBestPractices.MVVM;

namespace AppName.ViewModels
{
    public class HomeViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<Brand> _brands;
        public ObservableCollection<Brand> Brands
        {
            get => _brands;
            set => SetProperty(ref _brands, value);
        }

        public IAsyncCommand LoadBrandsCommand { get; set; }

        private bool _loadingBrands;
        public bool LoadingBrands
        {
            get => _loadingBrands;
            set => SetProperty(ref _loadingBrands, value);
        }

        public HomeViewModel()
        {
            LoadBrandsCommand = new AsyncCommand(LoadBrands, _ => !LoadingBrands);
            LoadBrandsCommand.Execute(null);
        }

        private async Task LoadBrands()
        {
            LoadingBrands = true;

            var brands = await BrandsDataStore.GetBrandsAsync();
            Brands = new ObservableCollection<Brand>(brands);

            LoadingBrands = false;
        }

        protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null)
        {
            if (EqualityComparer<T>.Default.Equals(backingStore, value))
                return false;

            backingStore = value;
            onChanged?.Invoke();
            OnPropertyChanged(propertyName);
            return true;
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var changed = PropertyChanged;
            if (changed == null)
                return;

            changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}

The problem I'm facing is that the BrandsCarouse.Brands property gets correctly notified of the change happening inside of HomeViewModel.LoadBrands but the BrandsCarousel.IsLoading does not. What could be the reason?


Looking for advice on iOS platform for Xamarin.Form development

$
0
0

Hello there,

We are getting into Xamarin.Form mobile app development. To build iOS apps we need iOS platform. We are considering the following options

  • Renting a cloud MAC
  • MacBook Air
  • MacBook Pro

Development will be done using Visual Studio for Mac, Community edition. Being new to MAC platform I'm not sure what would be an ideal system configuration for MAC. Can Xamarin.Andriod development be done on MAC using Visual Studio for Mac?

Joe

DB Locked in Android SQLite Xamarin Forms

$
0
0

I'm working on a App that have more than 50 tables and can work without internet connection, so in background the app can sync up with the API and get all the information and make the CRUD operation in local.

Sometimes when the app is sync up with the API, I'm getting the error "database is LOCKED", when I'm making another operation on the App.

So I need help to solve this, I know that there are a lot of post about this problem, but base on my implamentation with my database, it seems not to be enough to solve my problem.

Nugets:
Xamarin.Forms 3.0.0 482510
sqlite-net-pcl 1.5.166-beta

I use a class DataService.cs where that class connect with the DataContext.cs and make the connection with database and methods CRUD.
All methods in the DataService have the same way to connect with DataContext

//This is a resume of DataService.cs
    public class DataService 
        {
            public T Insert<T>(T model)
            {
                try
                {
                    using (var da = new DataContext())
                    {
                        da.Insert(model);
                        return model;
                    }
                }
                catch (Exception error)
                {
                    error.ToString();
                    return model;
                }
            }
    }

In DataContext.cs we have the connection with the local database and all the methods with the local database .
All methods have the collisionLock (to avoid conflict with database) and cnn.Dispose() (To close connection with the database and avoid the error Fatal signal 11 (SIGSEGV));

DataContext.cs

public interface IBusinessEntity
    {
        int ID { get; set; }
    }

  //This is a resume of DataContext.cs
    public class DataContext : IDisposable
    {
        #region Attributes
        public SQLiteConnection cnn;
        private static object collisionLock = new object();
        #endregion

        #region Constructors
        public DataContext()
        {
            cnn = DependencyService.Get<IConfiguracion>().GetConnection();
...
} 
        #endregion

        #region MetodosGenericosZulu
        public void Insert<T>(T model)
        {
            try
            {
                // Use locks to avoid database collisions
                lock (collisionLock)
                {
                    cnn.Insert(model);
                    cnn.Dispose();
                }
            }
            catch (Exception error)
            {
                Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Un error a ocurrido con la DB (Insert): " + error.Message.ToString(),
                    "Ok");
            }
        }

        public void Update<T>(T model)
        {
            try
            {
                lock (collisionLock)
                {
                    cnn.Update(model);
                    cnn.Dispose();
                }
            }
            catch (Exception error)
            {
                Application.Current.MainPage.DisplayAlert(
                                    "Error",
                                    "Un error a ocurrido con la DB (Actualizar): " + error.Message.ToString(),
                                    "Ok");
            }
        }

        ...
        #endregion
}
}

Implentation on Android project.

public class Configuracion : IConfiguracion
    {
        public Configuracion(){ }

        public SQLite.SQLiteConnection GetConnection()
        {
                var sqliteFileName = "FN_Desarrollo.db3";
                string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                var path = Path.Combine(documentsPath, sqliteFileName);
              var  conn = new SQLite.SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);

            return conn;
        }
    }

So I need your help guys to solve the problem (database locked) and review if my implementation with the SQLite is OK.

I'm hearing all the suggestions.

Thanks in advance.

Where is my binding context ?

$
0
0

I have a basic Xamarin Forms App... Started with Empty template VS 2019. Created a "Start.xaml / Start.cs" Start Page. Added a StartViewModel.cs. All very basic and generic... I added and ObservableCollection DisplayItems... This is a very generic list of configuration elements and just displays them in a very pretty little list... Everything works great...

After some rework of the "Model" (the DisplayItem Class)... I began pulling information for the model from a web service to enhance the information in the model... Again... very simple, and now, what began as a static list of 5 or 6 properties in my class, has grown to 13 properties where a majority of the information is pulled from the internet at regular intervals... Again, everything works perfectly... The one thing I needed to do is ensure that the information was saved locally... I considered using SQLite, but that is far more robust than i required for this proof of concept app. I decided to save it to a JSON file locally... So, I added Newtonsoft, and saved the data, again with some minor modifications to the DisplayItems class. The way this was handled was in the OnSleep method inside of App.cs, where the oncreate looks like the code below.

Again, everything works as expected. The file is saved locally, and the app uses the local copy when started, which makes the app very responsive... with the MVVM architecture the app updates the items in my view as the data is updated asynchronously... very slick and effective...

My next step was to build a details page for the finite detail that was captured from the web. I added a details page to the Views, added a ViewModel for the detail, passed the displayitem object into the constructor of the details page and then changed the App.cs constructor code from; MainPage = new Start(); to => MainPage = new NavigationPage( new Start() );

Now, when the app goes to sleep (or begins shutdown), the data is not saved because MainPage is no longer a standard ContentPage, but a NavigationPage object, and I no longer have access to the BindingContext (the viewmodel of the start page). I have tried several approaches, but nothing seems to save my list to json on sleep... the references to the ObservableList DisplayList in the ViewModel cannot be found because the BindingContext is null for Start Page...

How do I regain access to the Start Page View Model from the context of App? Any help would be appreciated,

    public App()
    {
        InitializeComponent();
        // old code
        // MainPage = new Start();
    MainPage = new NavigationPage( new Start() );
    }

    protected override void OnStart()
    {
    }

    protected override void OnSleep()
    {
        FileOperations.SaveDisplayJsonData((MainPage.BindingContext as StartViewModel).DisplayList.ToList());
    }

    protected override void OnResume()
    {
    }

Shell - How add programmatically sub menu item in flyout menu.

$
0
0

Hi, how add sub menu item in flyout menu programmatically?

My goal:

-MainMenuElement-01
-------SubMenuElement-01
-------SubMenuElement-02
-------SubMenuElement-03
--------------...
-MainMenuElement-02
-MainMenuElement-03

I can add programmatically MainMenuElement, but I can't add SubMenuElement in MainMenuElement.
I will be grateful for your help.

RG.PopupPage is calling OnDisappearingAnimationBeginAsync immediately on opening

$
0
0

I have a Xamarin Forms app which is mainly deploying to a UWP project. I have a popup to display a delete confirmation to the user when they start to delete a data element. The dialog is appearing but immediately dismissing. When I run in the debugger I am seeing that the OnAppearingAnimationEndAsync method is called and immediately after that the OnDisappearingAnimationBeginAsync method is called and the dialog dismisses.

The invoking code looks like:
public async Task ConfirmDeleteAsync(Frame cell)
{
RemoveRunContentView entryView = new RemoveRunContentView(TestRunItem);
InputAlertDialogBase deleteConfirmPopup =
new InputAlertDialogBase(entryView)
{
IsAnimationEnabled = false,
CloseWhenBackgroundIsClicked = false
};

                entryView.EnterButtonEventHandler += (sender, obj) =>
            {
                bool confirmDelete = ((RemoveRunContentView)sender).Result;

                if (confirmDelete)
                {
                    DeleteRun(TestRunItem);
                }
                PopupNavigation.Instance.PopAsync();

            };

            entryView.CancelButtonEventHandler += (sender, obj) =>
            {
                // Do Validation and decide if it should close
                deleteConfirmPopup.PageClosedTaskCompletionSource.SetResult(false);
                cell.Opacity = 1.0;
                PopupNavigation.Instance.PopAsync();
            };

            await PopupNavigation.Instance.PushAsync(deleteConfirmPopup);
        }

The await on the second to last line seems to not wait but continues on.

Does any one have any suggestions for fixing this?

TIA,
Ron L

Shell - How add programmatically sub menu item in flyout menu.

$
0
0

Hi, how add sub menu item in flyout menu programmatically?

My goal:

-MainMenuElement-01
-------SubMenuElement-01
-------SubMenuElement-02
-------SubMenuElement-03
--------------...
-MainMenuElement-02
-MainMenuElement-03

I can add programmatically MainMenuElement, but I can't add SubMenuElement in MainMenuElement.
I will be grateful for your help.

First WebRequest slow.

$
0
0

I've made an app that's suppossed to make several requests to a Website.
When sending the first request using WebRequests, the process is extremely slow.
Being new to Xamarin I obviously tried google, but alas, no solution found.
That is why, I'm turning towards you for help.

I ran the exact same sequence of requests twice on an Android Emulator. You can see the Debug Log, and the code used below.
The Website requested to uses SSL, eg. HTTPS:// example.com/

My Debug Log:
pastebin.com/8DyfPPFf

My code snippet:
pastebin.com/HTSCHy4i


Error during release build

$
0
0

Unerwarteter Fehler bei der LinkAssemblies-Aufgabe.
Mono.Linker.MarkException: Error processing method: 'Android.Views.ScaleGestureDetector Xamarin.Forms.Platform.Android.GestureManager::InitializeScaleDetector()' in assembly: 'Xamarin.Forms.Platform.Android.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Void Android.Support.V4.View.ScaleGestureDetectorCompat::SetQuickScaleEnabled(Android.Views.ScaleGestureDetector,System.Boolean)
bei Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference reference)
bei Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
bei Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
bei Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
bei Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
bei Mono.Linker.Steps.MarkStep.ProcessQueue()
--- Ende der internen Ausnahmestapelüberwachung ---
bei Mono.Linker.Steps.MarkStep.ProcessQueue()
bei Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
bei Mono.Linker.Steps.MarkStep.Process()
bei MonoDroid.Tuner.MonoDroidMarkStep.Process(LinkContext context)
bei Mono.Linker.Pipeline.Process(LinkContext context)
bei MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
bei Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
bei Xamarin.Android.Tasks.LinkAssemblies.Execute()
bei Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
bei Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() Retailer.Android

Hello,
my code shows this error trying to build a release version.

Can someone explain me what
s happend?

how can i update a listview with a button?

$
0
0

I am making a clone of a social network and in a list of comments.
I want to register one and instantly the list is updated and the record I made appears.

How can I display an image in a list?

$
0
0

I want to put a binded image and in my viewmodel pass the image to ImageSource.

This my Code.

Code XAML

Code ViewModel

And this my result
I get blank

Native Forms in UWP app - why doesn't it resize with the window?

$
0
0

I have a very basic UWP page with a Native Forms Content Page in it with an image. I want the image to fill the width of the UWP page. The image fills nicely when the app first starts, but when you resize the window the image doesn't change size. I was able to find a workaround to cause the image to resize, but I feel like it shouldn't be necessary. Below find the very basic page code, with the workaround bits notated by comments. It looks like the SizeChanged events are not firing as I would expect. Some examples:

  • Without the workaround lines included, frameworkElement.SizeChanged only fires when the window gets bigger than the initial size
  • formsPage.SizeChanged only fires when the Content = frameworkElement; line of the workaround is included, but if only that is included (and NOT formsPage.Layout(new Rectangle(0,0,-1,-1));) the image does resize but it only gets larger as you resize, it never gets smaller

Of course I'll file a bug for this if I'm not missing anything, but I wanted to check here first.

public MainPage()
{
    InitializeComponent();
    var formsPage = new ContentPage
    {
        BackgroundColor = Color.Yellow,
        Content = new StackLayout
        {
            BackgroundColor = Color.Blue,
            Children =
            {
                new Image
                {
                    Source = ImageSource.FromFile("Assets/xamLogo.png"),
                    BackgroundColor = Color.White
                }
            }
        }
    };
    var frameworkElement = formsPage.CreateFrameworkElement();
    formsPage.SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("plain forms page size change called");
    };
    frameworkElement.SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("forms page (as framework element) size change called");
    };
    SizeChanged += (sender, args) =>
    {
        Debug.WriteLine("top level uwp page size change called ");

        // BELOW two lines are a workaround, should this be needed!?
        formsPage.Layout(new Rectangle(0,0,-1,-1));
        Content = frameworkElement;
        //
    };
    Content = frameworkElement;
}

SQLite.SQLiteException: database disk image is malformed in xamarin.forms application

$
0
0

I have created a xamarin.forms application and ship a sqlite database with the application, im getting the following error:

database disk image is malformed.

This is the stacktrace:

SQLite3.Prepare2 (SQLitePCL.sqlite3 db, System.String query)
SQLiteCommand.Prepare ()
SQLiteCommand+<ExecuteDeferredQuery>d__12`1[T].MoveNext ()
List`1[T].AddEnumerable (System.Collections.Generic.IEnumerable`1[T] enumerable)
System.Collections.Generic.List`1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) [0x00062] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
Enumerable.ToList[TSource] (System.Collections.Generic.IEnumerable`1[T] source)
SQLiteCommand.ExecuteQuery[T] ()
SQLiteConnection.Query[T] (System.String query, System.Object[] args)
SQLiteAsyncConnection+<>c__DisplayClass28_0`1[T].<QueryAsync>b__0 ()
Task`1[TResult].InnerInvoke ()
Task.Execute ()
MyApp+<LoadDocFromDB>d__18.MoveNext ()
VolumeView+<VolumesListView_ItemSelected>d__13.MoveNext ()
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state)
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) System.Object.17(intptr,intptr)

This seem to happen sometimes, any clue what might be causing this?

Is it possible, to define a text file as asset in the platform independent part of the App?

$
0
0

If yes, how is it done and how is the file accessed in MainPage.xaml.cs?

Thank you very much in advance!
Kind regards,
wa

SQLite.SQLiteException: database disk image is malformed in xamarin.forms application

$
0
0

I have created a xamarin.forms application and ship a sqlite database with the application, im getting the following error:

database disk image is malformed.

This is the stacktrace:

SQLite3.Prepare2 (SQLitePCL.sqlite3 db, System.String query)
SQLiteCommand.Prepare ()
SQLiteCommand+<ExecuteDeferredQuery>d__12`1[T].MoveNext ()
List`1[T].AddEnumerable (System.Collections.Generic.IEnumerable`1[T] enumerable)
System.Collections.Generic.List`1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) [0x00062] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
Enumerable.ToList[TSource] (System.Collections.Generic.IEnumerable`1[T] source)
SQLiteCommand.ExecuteQuery[T] ()
SQLiteConnection.Query[T] (System.String query, System.Object[] args)
SQLiteAsyncConnection+<>c__DisplayClass28_0`1[T].<QueryAsync>b__0 ()
Task`1[TResult].InnerInvoke ()
Task.Execute ()
MyApp+<LoadDocFromDB>d__18.MoveNext ()
VolumeView+<VolumesListView_ItemSelected>d__13.MoveNext ()
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state)
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) System.Object.17(intptr,intptr)

This seem to happen sometimes, any clue what might be causing this?


Xamarin Shell ToolBarItem Image from storage

$
0
0

Hi,

I am a newbie at Xamarin…. So I would appreciate any help…

My app allows a user to select a profile picture - using instructions from:
ttps://lalorosas.com/blog/xamarin-forms-selecting-image-from-the-gallery

My app then saves the image and is able to reload the image into an ImageButton successfully using:
ttps://stackoverflow.com/questions/51038251/how-to-download-image-and-save-it-in-local-storage-using-xamarin-forms

I want to be able to reload the image from the database and put the image into the SHELL 
TOOLBARITEM and I haven’t been able to find instructions on that.

Can someone point me in the right direction.

Error when creating repeated local notifications using Xamarin.Forms on Android

$
0
0

I have been searching for how to create repeated local notifications, for instance a reminders app, I want to implement this logic on my xamarin.forms app so I have been testing with this piece of code (and understanding it) that I found on the web but the following error just I dont understand it.

Failed to create JavaTypeInfo for class: Android.Support.V4.View.Accessibility.AccessibilityManagerCompat/IAccessibilityStateChangeListenerImplementor due to MAX_PATH: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\andre\source\repos\LocalRepeatedNotificationsApp\LocalRepeatedNotificationsApp\LocalRepeatedNotificationsApp.Android\obj\Debug\90\android\src\mono\android\support\v4\view\accessibility\AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor.java'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalDelete(String path, Boolean checkHost)
   at System.IO.File.Delete(String path)
   at Xamarin.Android.Tools.Files.CopyIfStreamChanged(Stream stream, String destination)
   at Xamarin.Android.Tasks.Generator.CreateJavaSources(TaskLoggingHelper log, IEnumerable`1 javaTypes, String outputPath, String applicationJavaClass, String androidSdkPlatform, Boolean useSharedRuntime, Boolean generateOnCreateOverrides, Boolean hasExportReference) LocalRepeatedNotificationsApp.Android           

My code for sending local notifications in a repeated way:

public class LocalNotificationService : ILocalNotificationService
    {
        int _notificationIconId { get; set; }
        readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        internal string _randomNumber;

        public void LocalNotification(string title, string body, int id, DateTime notifyTime)
        {

            //long repeateDay = 1000 * 60 * 60 * 24;    
            long repeateForMinute = 60000; // In milliseconds   
            long totalMilliSeconds = (long)(notifyTime.ToUniversalTime() - _jan1st1970).TotalMilliseconds;
            if (totalMilliSeconds < JavaSystem.CurrentTimeMillis())
            {
                totalMilliSeconds = totalMilliSeconds + repeateForMinute;
            }

            var intent = CreateIntent(id);
            var localNotification = new LocalNotification();
            localNotification.Title = title;
            localNotification.Body = body;
            localNotification.Id = id;
            localNotification.NotifyTime = notifyTime;

            if (_notificationIconId != 0)
            {
                localNotification.IconId = _notificationIconId;
            }
            else
            {
                localNotification.IconId = Resource.Drawable.OlympiaLogo;
            }

            var serializedNotification = SerializeNotification(localNotification);
            intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);

            Random generator = new Random();
            _randomNumber = generator.Next(100000, 999999).ToString("D6");

            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.SetRepeating(AlarmType.RtcWakeup, totalMilliSeconds, repeateForMinute, pendingIntent);
        }

        public void Cancel(int id)
        {

            var intent = CreateIntent(id);
            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.Cancel(pendingIntent);
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.CancelAll();
            notificationManager.Cancel(id);
        }

        public static Intent GetLauncherActivity()
        {

            var packageName = Application.Context.PackageName;
            return Application.Context.PackageManager.GetLaunchIntentForPackage(packageName);
        }


        private Intent CreateIntent(int id)
        {

            return new Intent(Application.Context, typeof(ScheduledAlarmHandler))
                .SetAction("LocalNotifierIntent" + id);
        }

        private AlarmManager GetAlarmManager()
        {

            var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
            return alarmManager;
        }

        private string SerializeNotification(LocalNotification notification)
        {

            var xmlSerializer = new XmlSerializer(notification.GetType());

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, notification);
                return stringWriter.ToString();
            }
        }
    }

    [BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]
    public class ScheduledAlarmHandler : BroadcastReceiver
    {

        public const string LocalNotificationKey = "LocalNotification";

        public override void OnReceive(Context context, Intent intent)
        {
            var extra = intent.GetStringExtra(LocalNotificationKey);
            var notification = DeserializeNotification(extra);
            //Generating notification    
            var builder = new NotificationCompat.Builder(Application.Context)
                .SetContentTitle(notification.Title)
                .SetContentText(notification.Body)
                .SetSmallIcon(notification.IconId)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
                .SetAutoCancel(true);

            var resultIntent = LocalNotificationService.GetLauncherActivity();
            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
            stackBuilder.AddNextIntent(resultIntent);

            Random random = new Random();
            int randomNumber = random.Next(9999 - 1000) + 1000;

            var resultPendingIntent =
                stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.Immutable);
            builder.SetContentIntent(resultPendingIntent);
            // Sending notification    
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.Notify(randomNumber, builder.Build());
        }

        private LocalNotification DeserializeNotification(string notificationString)
        {

            var xmlSerializer = new XmlSerializer(typeof(LocalNotification));
            using (var stringReader = new StringReader(notificationString))
            {
                var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);
                return notification;
            }
        }
    }

I am usign DependencyService to achieve this (my assembly is defined on the scope of my namespace but I havent included it for showing the problem)
Any help please?

Detecting if user switched to another app

$
0
0

Hi All,

Let's say we are developing an online exam kind of solution and we want to detect if user is leaving the app and goes to some other application(e.g. google in browser) to find the answers for exam questions. What will be the good approach to implement this? Our app is on Android as well as Windows.

Thanks & Regards.

Xamarin forms: Webview for playing video is not working in iPhone?

$
0
0

I am using Webview for playing video and audio and it is working fine on android and iPhone simulators. But on the real iPhone, video playing is not working fine.

For playing the video on the iPhone, I need to tap the video play button multiple times. After that also it takes a long time to play the video. Another important thing is my video links have no video format(.mp4,.mkv).

XAML

<WebView 
    x:Name="web_view"
    HeightRequest="200"
    WidthRequest="200"
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand"/>

XAML.cs

web_view.Source = "https://player.vimeo.com/video/303543322";

I tried Plugin.MediaManager.Forms, but it needs video format(.mp4,.mkv) in the link, otherwise it will not work. So is there any way to fix this issue in webview itself or should I go for any other player(video and audio) which supports playing video without video format?

Receive message Shared mono runtime is endabled for Firstpage

$
0
0

When I attempted to archive I get message THE ARCHIVE PROCESS HAS FAILED - SHARED MONO RUNTIME IS ENABLE FRO FIRSTPAGE.

Viewing all 91519 articles
Browse latest View live