EzDev.org

FreshMvvm

FreshMvvm is a super light Mvvm Framework designed specifically for Xamarin.Forms. It's designed to be Easy, Simple and Flexible.


Android application throwing: Java.Lang.IllegalStateException, with message: Can not perform this action after onSaveInstanceState

To shorten the problem: I am developing an android application which requires users to log in, and since multiple users could be logged in at the same time, I want to cycle between the authenticated users using NFC touch cards. Everything works fine except after using ZXing.Mobile bar-code scanner, when code returns from scanning any bar-code, and tries to push a page model, this particular exception is being thrown Java.Lang.IllegalStateException: Can not perform this action after onSaveInstanceState. Please note that I am using Xamarin.Forms, FreshMVVM, ZXing.Mobile, and of course C#.

Fragments of code used:

AndroidManifest.xml:

<activity android:name="com.name.SplashActivity">
    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.MAIN" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="application/com.name.nfc" />
    </intent-filter>
</activity>
<activity android:name="com.name.MainActivity">
</activity>

The above code is used to enable the application to launch using NFC tags. SplashActivity launches MainActivity.

SplashActivity.cs:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    StartActivity(typeof(MainActivity));
}

protected override void OnResume()
{
    base.OnResume();

    if (NfcAdapter.ActionNdefDiscovered == Intent.Action)
    {
        ProcessIntent(Intent);
    }
}

protected override void OnNewIntent(Intent intent)
{
    Intent = intent;
}

public void ProcessIntent(Intent intent)
{
    //Code omitted to simplify the question.
}

Above code is shown just to know how I am using the NFC touch event.

Code to open the bar-code scanner from main page model:

public ICommand OpenCameraCommand => new Command(async () =>
{
    IsAvailable = false;
    ((Command) OpenCameraCommand).ChangeCanExecute();
    string checkBarcode = await _scanService.CameraScanAsync().ConfigureAwait(true);
    if (!string.IsNullOrWhiteSpace(checkBarcode))
    {
        Barcode = checkBarcode;
    }
    IsAvailable = true;
}, () => IsAvailable);

From scan service:

public async Task<string> CameraScanAsync()
{
    //AutoFocus code omitted to simplify the question

    Result result = await _mobileBarcodeScanner.Scan(new MobileBarcodeScanningOptions { PossibleFormats = _listOfBarcodeFormats }).ConfigureAwait(false);

    return result == null ? string.Empty : result.Text;
}

EDIT: code containing the push page model method:

switch (response.Status)
{
    case Case.Second:
        await CoreMethods.PushPageModel<SecondaryPageModel>(response).ConfigureAwait(true);
        Barcode = string.Empty;
        return;
    case Case.Third:
        await CoreMethods.PushPageModel<ThirdPageModel>(response).ConfigureAwait(true);
        Barcode = string.Empty;
        return;
    case Case.Fourth:
        await CoreMethods.PushPageModel<FourthPageModel>(response).ConfigureAwait(true);
        Barcode = string.Empty;
        return;
    case Case.Invalid:
        break;
    default:
        throw new InvalidOperationException();
}

This code is fired directly after returning from scanning a bar-code.
END EDIT

All of this works after the NFC card is being touched and the application launched, until hitting the next line of code. After a bar-code is returned from the scanner:
await CoreMethods.PushPageModel<SecondaryPageModel>(response).ConfigureAwait(true);

The exception is being thrown right here. I debugged my code to check what's going on. When the camera is open, it first fires MainActivity OnSaveInstanceState event, after successfully scanning a bar-code, MainActivity OnResume > MainActivity OnPostResume events are fired in that order. Then the PushPageModel method is called. Note that when I manually enter the bar-code in the relative field, everything works fine, it's just the scanner that throws this exception.

I have searched for solutions here in SO. I found some answers that says to opt-out the base.OnSaveInstanceState() line, I tried that with no luck, another answer said to enter junk values to work around the issue, tried that with no luck as well. I tried different launch modes in the AndroidManifest file like singleTop or singleTask or singleInstance with no luck as well.

I will be glad with any help that could be given. Thanks in advance.


Source: (StackOverflow)

Listen to ItemTapped Event in FreshMvvm

In my project I have a list view, now listening to SelectedItem change is easy, every tutorial has that, but I can't find anything on using ItemTapped event.

What do I bind the event to in the modelPage?

Thanks,

Mike


Source: (StackOverflow)

Xamarin forms FreshMVVM: custom styling for side drawer navigation bar

Using Xamarin Forms and FreshMVVM to develop a MasterDetailPage cross platform app, I am looking for a way to apply custom styling to the side drawer navigation bar (increase line height, different background color, change font color/size, ...).

Any hints how to achieve that? Thanks in advance.


Source: (StackOverflow)

XAML WebView binding to HTML source not working

I have a XAML page layout defined that includes a WebView populated from an HTML string:

<WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Flag.Description}" />
<!--    <HtmlWebViewSource Html="&lt;html>&lt;body>&lt;p>The HTML string.&lt;/p>&lt;/body>&lt;/html>" />-->
    </WebView.Source>
</WebView>

When I hard code the string into the XAML it displays correctly, but it will not bind to the Flag.Description string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.


Source: (StackOverflow)

Xamarin Forms: MasterPage Helper class

My current app has multiple master detail pages. I want to create a helper class which has a function that accepts list of PageModels-Pages( ViewModels-views ) which I can iterate through and create master detail pages.

MyCurrent Code:

public static Page SetupMasterDetailNav<T,U>( Dictionary<T,string> Menu) 
        where T : class 
         //In Dictionary T is ViewModel(PageModel) , 
          String is name displayed on Master page  
    {
        var masterDetail = new FreshMasterDetailNavigationContainer();

        foreach (KeyValuePair<T,string> item in Menu)
        {
            masterDetail.AddPage<item.Key>(item.Value); 
        }
        masterDetail.Init("");
        return masterDetail;
    }

This code doesn't work.It tells me item.key is a variable and cannot be used as a type Can any one suggest me a better approach or how else I can achieve my goal ?


Source: (StackOverflow)

freshmvvm access PageModel from Page code behind

Im using xamarin forms with freshmvvm framework.

I would like to know how I can skip using xaml, and just access binding data from code behind in c#.

Are there any code samples that could help?


Source: (StackOverflow)

Xamarin Forms Tabbed Navigation child of Master Detail Page on UWP

I'm implementing a Master Detail navigation using Xamarin Forms (v2.3.1.114) and FreshMVVM where the first page is a tabbed navigation. For the implementation, I'm using FreshMVVM custom Navigation Sample.

The navigation works fine on Android and iOS but on UWP the Master Navigation Button doesn't show up.

Android vs UWP enter image description here

Here is a part of my navigation code

FreshTabbedNavigationContainer _mainTabs;
void Setup()
    {
        _mainTabs = new FreshTabbedNavigationContainer();
        _mainTabs.AddTab<MyRewardsPageModel>("My Rewards", null);
        _mainTabs.AddTab<MapPageModel>("Map", null);
        _mainTabs.AddTab<NearbyPageModel>("Near You", null);
        _contactusPage = FreshPageModelResolver.ResolvePageModel<ContactUsPageModel>();
        _aboutUsPage = FreshPageModelResolver.ResolvePageModel<AboutUsPageModel>();
    }

void CreateMenuPage(string menu)
    {
        var menuPage = new ContentPage { Title = menu };
        var listView = new ListView { ItemsSource = new string[] { "Home", "Contact Us", "About Us" } };
        listView.ItemSelected += (sender, args) =>
        {
            switch ((string)args.SelectedItem)
            {
                case "Home":
                    Detail = _mainTabs;
                    break;
                case "Contact Us":
                    Detail = new NavigationPage(_contactusPage);
                    break;
                case "About Us":
                    Detail = new NavigationPage(_contactusPage);
                    break;
                default:
                    break;
            }
            IsPresented = false;
        };
        IsPresented = true;
        menuPage.Content = listView;
        Detail = _mainTabs;
        Master = new NavigationPage(menuPage)
        {
            Title = menu,
            BarBackgroundColor = Color.Green,
            BarTextColor = Color.Black
        };
    }

Is this a Xamarin Forms bug or is it my implementation? Any suggestion is highly appreciated


Source: (StackOverflow)

How do you style a master page in FreshMvvm MasterDetailContainer

Is there a way to apply styling to the menu in the Master of FreshMvvm MasterDetailNavigationContainer. A simple styling could be a background color or changing the font of the menu items. I Can see the menu is just a simple ContentPage with a ListView, but no hooks?


Source: (StackOverflow)

Implement an Modal with a ObservableCollection

I'm using freshmvvm.

Modal

public class Expense : INotifyPropertyChanged
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ObservableCollection<ImageSource> Images { get; set; }//here
    public event PropertyChangedEventHandler PropertyChanged;
}

I would like to give Images properties like (name, type, source)

 public ObservableCollection<ImageSource> Images { 
   public string name { get; set; }
   public string type { get; set; }
   public ImageSource source { get; set; }
 }

Source: (StackOverflow)

Binding with BasePage in Xamarin Forms

I am implementing a Xamarin app with FreshMVVM framework and I want to use a BasePage to share some code among Pages. The problem is that when I need to bind some Properties in the MainPage.xaml I have to specify the Source in this way to make it working: Text="{Binding Title, Source={x:Reference mainPage}}". Otherwise without Source Binding doesn't work. Ok, I get it but is this the right way? Is there another way to achieve the same result? What about when I have plenty of bindings in a page? For instance, is it possible "setting" the Source at un upper level, because in my opinion setting the same Source for each Binding is very annoying.

BasePage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestXamarin.BasePage"
             x:Name="basePage">
    <ContentView>
        <StackLayout Orientation="Vertical">
            <Label Text="HEADER" FontSize="Large"/>
            <Label Text="{Binding Text, Source={x:Reference basePage}}" FontSize="Large"/>
            <ContentPresenter BindingContext="{Binding Parent.BindingContext}" 
                              Content="{Binding PageContent, Source={x:Reference basePage}}" />
        </StackLayout>
    </ContentView>
</ContentPage>

BasePage.xaml.cs

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestXamarin
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class BasePage : ContentPage
	{
		public static readonly BindableProperty TextProperty = BindableProperty.Create(
			   nameof(Text),
			   typeof(string),
			   typeof(BasePage));

		public string Text
		{
			get { return (string)GetValue(TextProperty); }
			set { SetValue(TextProperty, value); }
		}

		public static readonly BindableProperty PageContentProperty = BindableProperty.Create(
			   nameof(PageContent),
			   typeof(object),
			   typeof(BasePage));

		public object PageContent
		{
				get { return GetValue(PageContentProperty); }
				set { SetValue(PageContentProperty, value); }
		}

		public BasePage()
		{
			InitializeComponent();
		}
	}
}

MainPage.xaml

<local:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:local="clr-namespace:TestXamarin"
                x:Class="TestXamarin.MainPage"
                Text="FROM MAIN PAGE"
                x:Name="mainPage">
    <local:BasePage.PageContent>
        <StackLayout>
            <Label Text="Body" FontSize="Large"/>
            <Label Text="{Binding Title, Source={x:Reference mainPage}}" FontSize="Large"/>
        </StackLayout>
    </local:BasePage.PageContent>
</local:BasePage>

MainPage.xaml.cs

public partial class MainPage : BasePage
	{
		public MainPage()
		{
			Title = "MAIN PAGE";

			InitializeComponent();
		}
	}


Source: (StackOverflow)

Xamarin.Forms set focus from mvvm ViewModel

I'm working on a chat application using Xamarin.Forms.

And I want to avoid to hide the keyboard when the Entry loses focus and button Send is clicked.

How can I do it on Android and iOS?

I use XF, full Mvvm without XAML(only C#)

Updated:

In page class:

private EntrySetBorder _newMessageEntry;
...
_newMessageEntry = new EntrySetBorder
{
    TextColor = Color.Black,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.End,
    Margin = new Thickness(0, 0, 5, 0)
};

In model class:

var entry = CurrentPage.FindByName<EntrySetBorder>("_newMessageEntry");
entry.Focus();

}


Source: (StackOverflow)

How to intercept WebView Navigating event in ViewModel

My app has a WebView for displaying some contact information. It has a link to a website that I want to load externally using Device.OpenUri(). I'm using FreshMvvm and I want to intercept the Navigating event from the WebView in the ViewModel and cancel the default action which would load the external page into the WebView.

I've tried using the Corcav.Behaviors plugin which does call my ViewModel command:

        <WebView
            HorizontalOptions="Fill" 
            VerticalOptions="FillAndExpand" 
            Source="{Binding WebViewSource}">
              <b:Interaction.Behaviors>
                <b:BehaviorCollection>
                    <b:EventToCommand
                        EventName="Navigating"
                        Command="{Binding NavigatingCommand}"
                        CommandParameter="{Binding}"/> <!-- what goes here -->
                </b:BehaviorCollection>
              </b:Interaction.Behaviors>
        </WebView>

But I'm not sure what the CommandParameter should be - I need the URI of the link that was tapped, and I don't know how to then prevent the default behaviour from occurring.

Is this the best approach or should I be looking at an alternative?


Source: (StackOverflow)

Xamarin Forms IoC containter + navigation service

  1. Does Xamarin.Forms have a built-in IoC navigation service? I mean something like Prism, where you could register your routes.
  2. If yes - where is the documentation?
  3. If not - will Xamarin.Forms have a built-in navigation service in near future?
  4. Also - if not - what would be the best MVVM fw for Xamarin.Android, Xamarin.iOS, Xamarin.WinXYZ and Xamarin.Forms? And why?

It seems to me that it comes down to battle between Prism and FreshMVVM - this brings me to my most important questions:

  1. Which of these two is performing better? (Which one is faster?)
  2. Which of these is more likely to lead the way of MVVM frameworks considering mobile development in the future?

Source: (StackOverflow)

FreshMvvm PushNewNavigationServiceModal not working

I'm trying to change from FreshNavigationContainer to FreshMasterDetailNavigationContainer when the user is loggedin within the method SuccessfulLogin by using freshMvvm method PushNewNavigationServiceModal but nothing is happening.

    public void SuccessfulLogin()
    {
        App.IsLoggedIn = true;
        var masterDetailNav = new FreshMasterDetailNavigationContainer();
        masterDetailNav.Init("Menu");
        masterDetailNav.AddPage<ProfilePageModel>("Profile", null);
        CoreMethods.PushNewNavigationServiceModal(masterDetailNav);
    }

Edit : I just noticed that after using this method navigation isn't working anymore.


Source: (StackOverflow)

Xamarin Forms: IOC in FreshMvvm

I am using Freshmvvm for my Xamarin forms project. I am using a camera and want to use platform specific features. So, I was wondering how can I use IOC controls to use platform specific feature.

Freshmvvm.FreshIOC.Container.Register<ICamera,Camera>();

If I call this code from the App class, Should I need to have camera class in both iOS and Android projects, if yes then how to let the app class know we want to implement a Camera class of one specific platform? or is there a better way to use IOC control and inject the interfaces into the contructors of the page models(view models) when we want to use it ?


Source: (StackOverflow)