MvvmCross – FlyoutNavigation, Hamburger Menu, Sliding Menu for Android Null Reference Exception on Fragment Shown Fix

Summary

The architecture I used in MvvmCross for a FlyoutNavigation/Hamburger Menu/Sliding Menu requires the developer to maintain ViewModel state for all of the fragments used within the menu. The original implementation did not provide such a service. On certain Android devices a null reference exception would be generated when the user navigated between fragments.

The fix described here is not a perfect solution, use with caution.

Original Articles

Source Code

https://github.com/benhysell/V.FlyoutTest

Issue

After using the slide out menu architecture in an iOS, Android, and Windows Phone app I started receiving bug reports from two different Android Samsung devices.

06-09 11:36:16.740 I/MonoDroid(21351): UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
06-09 11:36:16.740 I/MonoDroid(21351): at V.JobTrak.Apps.Droid.Views.EnterTimeView.OnCreateView (Android.Views.LayoutInflater,Android.Views.ViewGroup,Android.OS.Bundle) <IL 0x000cf, 0x00588>
06-09 11:36:16.740 I/MonoDroid(21351): at Android.Support.V4.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_ (intptr,intptr,intptr,intptr,intptr) <IL 0x00026, 0x0019f>
06-09 11:36:16.740 I/MonoDroid(21351): at (wrapper dynamic-method) object.d4c53d5a-8a99-43f6-bd55-88a30287aec2 (intptr,intptr,intptr,intptr,intptr) <IL 0x00023, 0x0005f>
An unhandled exception occured.

Unhandled Exception:

Java.Lang.Throwable: Loading...

06-09 11:36:20.620 D/HockeyApp(21351): Writing unhandled exception to: /data/data/com.droid.apps.jobtrak.v/files/f6e8f1e8-532a-49e9-99e2-00970568f77a.stacktrace
06-09 11:36:20.620 E/mono-rt (21351): [ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.Throwable: Exception of type 'Java.Lang.Throwable' was thrown.
06-09 11:36:20.620 E/mono-rt (21351): at Android.Runtime.JNIEnv.NewString (string) <IL 0x0004c, 0x00260>
06-09 11:36:20.620 E/mono-rt (21351): java.lang.Throwable: System.NullReferenceException: Object referenc06-09 11:36:20.620 E/mono-rt (21351): at Android.Util.Log.Info (string,string) <IL 0x0002e, 0x00127>
06-09 11:36:20.620 E/mono-rt (21351): at Android.Runtime.AndroidEnvironment.UnhandledException (System.Exception) <IL 0x00010, 0x00093>
06-09 11:36:20.620 E/mono-rt (21351): at (wrapper dynamic-method) object.da665a14-2c2b-48b2-9db0-7303fcb7fde2 (intptr,intptr) <IL 0x00029, 0x0008f>
06-09 11:36:20.620 E/mono-rt (21351): at (wrapper native-to-managed) object.da665a14-2c2b-48b2-9db0-7303fcb7fde2 (intptr,intptr) <IL 0x0001a, 0x0006b>
06-09 11:36:20.620 E/mono-rt (21351): 
06-09 11:36:20.620 E/mono-rt (21351):   --- End of managed exception stack trace ---
06-09 11:36:20.620 E/mono-rt (21351): java.lang.Throwable: System.NullReferenceException: Object reference not set to an instance of an object
06-09 11:36:20.620 E/mono-rt (21351): at V.JobTrak.Apps.Droid.Views.EnterTimeView.OnCreateView (Android.Views.LayoutInflater,Android.Views.ViewGroup,Android.OS.Bundle) <IL 0x000cf, 0x00588>
06-09 11:36:20.620 E/mono-rt (21351): at Android.Support.V4.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_ (intptr,intptr,intptr,intptr,intptr)
The program 'Mono' has exited with code 0 (0x0).

Same crash, two different devices. I couldn’t for the life of me reproduce it on my Nexus 5 and was at a loss as to what was going on.

Getting Help

I turned to StackOverflow, http://stackoverflow.com/questions/24145410/mvvmcross-android-null-reference-for-viewmodel-when-reloading-fragments and almost immediately I received a response from Stuart Lodge the creator of MvvmCross.

From his answer on StackOverflow:

From your code, it looks like you are manually setting the ViewModel's of your fragments when you first create them: frag.ViewModel = viewModelLocal; [https://github.com/benhysell/V.FlyoutTest/blob/master/V.FlyoutTest.Droid/Views/HomeView.cs#L153](https://github.com/benhysell/V.FlyoutTest/blob/master/V.FlyoutTest.Droid/Views/HomeView.cs#L153)

Which, sure enough, that was exactly what was going on, from the HomeView.cs\Show() in the Android project:

var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var viewModelLocal = loaderService.LoadViewModel(request, null /* saved state */);
frag.ViewModel = viewModelLocal;

Bottom line, since I’ve created the ViewModel in my HomeView for a View I need to make sure it gets recreated if it is ever unloaded from memory.

Reproducing the Error with My Device

The real kicker with this issue is I could not reproduce it on my own device, or almost any other device I tested with. The error only showed up on a Samsung S3 and S5. I turned to the jabbr.net chat room for MvvmCross, https://jabbr.net/#/rooms/mvvmcross, for advice. It was Stuart Lodge who turned me onto a devious little setting in the Android Developer Options Menu called ‘Don’t Keep Activities’.

Screenshot_2014-06-28-23-09-51

Check that box and Android will ensure that the second you navigate away from an activity it is completely dumped from memory. When I checked it on the N5 I could re-create the crashes I was seeing in the field!

Fixing the Crashes

I do not know the proper, “Ivory Tower” method to fix this particular issue. I stumbled around for a few days trying different methods to address the null reference exception, but discovered this is a non-trivial issue. From MvvmCross’ GitHub issue tracker: Setting ViewModel property on a Fragment is not Correct

``` var viewModelLoader = Mvx.Resolve(); fragment.ViewModel = viewModelLoader.LoadViewModel(request, null); ``` This is incorrect because Fragments are managed by a FragmentManager and each Fragments lifecycle is at the mercy of that manager and Android. At any time your Fragment may be destroyed and the FragmentManager's job is to recreate it. When it gets recreated it will no longer have the ViewModel you gave it and this will cause problems in the program. This pattern works in ideal situations but will break in many others....

The issue, as of publishing this post, is still open.

Warning - This Fix is a Hack

Realizing the proper fix was currently beyond my capability I went for a fix that appears to work. Since the fix has been implemented the app no longer crashes due to this bug. Be warned, this is a hack, understand it before you use it.

Steps Taken to Fix the Issue

  1. In HomeViewModel we’ll save the ViewModels for the fragments we are creating when OnSaveInstanceState(Bundle outState) is called in hopes MvvmCross will properly save the state of our ViewModels if they are properties of the HomeViewModel
  2. In the OnCreate() method we’ll attempt to restore the ViewModel of the fragment we are about to show, and if we can’t we’ll create a new one.

Modifying HomeViewModel

In the HomeViewModel we’ll add public properties for each of the ViewModels of our fragments.

public class HomeViewModel : BaseViewModel
{
    //allows us to save state for Android
    public EnterTimeViewModel EnterTimeViewModelFragment;
    public CreateNewJobViewModel CreateNewJobViewModelFragment;

Creating Our Fragments

When we create our fragments we are going to add a tag to the fragment when we add it to the SupportFragmentManager. We’ll use the fragment’s title property as the tag, thus later on we can check the SupportFragmentManager using the title of the fragment to see if the fragment exists and if it has a valid ViewModel attached to it.

this.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, frag, title).Commit();

Saving Fragment State

We’ll iterate through all of the fragments in our SupportFragmentManager, grab their ViewModels and place them in our HomeViewModel with the hopes that if the HomeViewModel is removed from memory the standard MvvmCross state saving mechanisms will also save the state of our fragment’s ViewModels.

        protected override void OnSaveInstanceState(Bundle outState)
        {
            SaveViewModelStates();
            base.OnSaveInstanceState(outState);
        }

        private void SaveViewModelStates()
        {
            //save all of the ViewModels for fragments
            var view = this.SupportFragmentManager.FindFragmentByTag("Enter Time") as EnterTimeView;
            if (null != view)
            {
                ViewModel.EnterTimeViewModelFragment = view.ViewModel as EnterTimeViewModel;
            }
            var view2 = this.SupportFragmentManager.FindFragmentByTag("Create New Job") as CreateNewJobView;
            if (null != view2)
            {
                ViewModel.CreateNewJobViewModelFragment = view2.ViewModel as CreateNewJobViewModel;
            }            
        }

Showing a Fragment

In the OnCreate() method we used to punt if we had any savedInstanceState data.

    if (null == savedInstanceState)
    {
        this.ViewModel.SelectMenuItemCommand.Execute(this.ViewModel.MenuItems[0]);
    }
}// end function

Now we will attempt to restore that state.

    if (null == savedInstanceState)
    {
        this.ViewModel.SelectMenuItemCommand.Execute(this.ViewModel.MenuItems[0]);
    }
    else
    {
        //restore viewModels if we have them
        RestoreViewModels();
    }
} //end of function            
 
/// <summary>
/// Restore view models to fragments if we have them and the fragments were created
/// </summary>
private void RestoreViewModels()
{
    var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
            
    var view = this.SupportFragmentManager.FindFragmentByTag("Enter Time") as EnterTimeView;
    if (null != view && null == view.ViewModel)
    {
        view.ViewModel = ViewModel.EnterTimeViewModelFragment ?? loaderService.LoadViewModel(new MvxViewModelRequest(typeof(EnterTimeViewModel), null, null, null), null) as EnterTimeViewModel;
    }
    var view2 = this.SupportFragmentManager.FindFragmentByTag("Create New Job") as CreateNewJobView;
    if (null != view2 && null == view2.ViewModel)
    {
        view2.ViewModel = ViewModel.CreateNewJobViewModelFragment ?? loaderService.LoadViewModel(new MvxViewModelRequest(typeof(CreateNewJobViewModel), null, null, null), null) as CreateNewJobViewModel;
    }            
}

We iterate through all of the fragments in the SupportFragmentManager checking to see if our fragment was created, and if so if the ViewModel is valid. If it is null attempt to grab it from the HomeViewModel instance we saved away, if that is also null create a new ViewModel for the fragment.

Conclusion

This solution is a hack, it is ugly, and in no means the proper way to account for this behavior on the Android platform. Case and point, in my testing I found often times the HomeViewModel would have a valid reference to my fragment’s ViewModels when I attempted to restore them in the RestoreViewModels(). I may just be fooling myself in my limited testing, and there is a good chance that step doesn’t do what I’m expecting it to do. However, the worst case in this situation is a new ViewModel is created for the fragment, ensuring we do not get a null reference exception when we attempt to load our fragment.

MvvmCross – FlyoutNavigation, Hamburger Menu, Sliding Menu for Android, iOS, and Windows Phone

Summary

Provide a unified architecture for a FlyoutNavigation/Hamburger Menu/Sliding Menu for Android, iOS, and Windows Phone 8 Silverlight using MvvmCross.

flyout menus # Source Code https://github.com/benhysell/V.FlyoutTest

Original Article

See - http://benjaminhysell.com/archive/2014/04/mvvmcross-flyoutnavigation-hamburger-menu-sliding-menu-for-android-and-ios/ for a walkthrough of the unified architecture for iOS and Android. This article expands upon that architecture to include Windows Phone 8.0 Silverlight.

Inspiration for Windows Phone 8.0 Silverlight Implementation

I had found a few Windows Phone slide out implementations, http://slideview.codeplex.com/, but attempting to tie them in with MvvmCross appeared to be a bit of a tall order, and for a while I had given up on my dream of unifying a slide out menu architecture for all three platforms.

Then I read this great article from Scott Hanselman http://www.hanselman.com/blog/XamarinFormsWriteOnceRunEverywhereANDBeNative.aspx talking about the new Xamarin.Forms where one could write all of their presentation code once, and have it natively drawn on each platform. The app used for the demo was a iOS, Android, and Windows Phone app with a slide out menu!

Source - https://github.com/jamesmontemagno/Hanselman.Forms

Astute readers will notice, James Montemagno was the inspiration for the Android slide out menu in my original article:

I took the evening and dissected the demo Xamarin.Forms app. iOS and Android implemented the familiar ‘hamburger’ in the upper left hand corner, that when pressed, would reveal other screens the user could navigate to. The Windows Phone however placed the button on the ApplicationBar, and when pushed showed a whole new page.

Inspired, I went back to Visual Studio and proceeded to provide a Windows Phone implementation of my slide out menu architecture.

Windows Phone Silverlight Implementation

As I said, this is not the traditional slide out menu for Windows Phone. If I must confess, I’m not a daily Windows Phone user, yet, but the days where I do use Windows Phone I find the slide out menu is not as prevalent on the platform as it is ingrained on iOS and Android. My slide out implementation is a “For Now” implementation, if the platform idioms change where a true slide out becomes the norm I’ll revisit the topic.

Solution

wp8 entertime

There are two major elements we need to implement for our Windows Phone solution: 1. The HomeView.xaml to hold our application menu 2. An ApplicationBar to hold our slide out menu icon on each of our root views

HomeView.xaml

The HomeView.xaml holds the list of other Views we could navigate to. For this example I kept things simple, placing the items in a ListBox. Since our HomeViewModel already has

private List<MenuViewModel> menuItems;
public List<MenuViewModel> MenuItems
{
    get { return this.menuItems; }
    set { this.menuItems = value; this.RaisePropertyChanged(() => this.MenuItems); }
}

We can bind to the MenuItems in our HomeView.xaml.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <StackPanel>
        <ListBox ItemsSource="{Binding MenuItems}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="24">
                        <TextBlock Text="{Binding Title}" Tap="UIElement_OnTap" FontSize="50" ></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</Grid>

HACK WARNING

Notice the Tap=UIElement_OnTap? In HomeView.xaml.cs It leads us to:

private void UIElement_OnTap(object sender, GestureEventArgs e)
{
    var selectedItem = ((HomeViewModel)ViewModel).MenuItems.FirstOrDefault(x => x.Title == ((TextBlock)sender).Text);
    if (null != selectedItem)
        ((HomeViewModel)ViewModel).SelectMenuItemCommand.Execute(selectedItem);
}

This allows us to figure out which cell the user pressed so we can navigate to the requested page. There are better ways to get this done, however I’m not a Windows Phone 8/MvvmCross master so I settled on this implementation for now.

Show the First View on Application Start

The only item left in our HomeView.xaml.cs is to navigate to the first view we would like our user to see when they launch the app. We accomplish that in the OnNavigatedTo

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (null == ViewModel)
    {
        base.OnNavigatedTo(e);

        var selectedItem = ((HomeViewModel)ViewModel).MenuItems.FirstOrDefault(x => x.Title == "Enter Time");
        if (null != selectedItem)
        ((HomeViewModel)ViewModel).SelectMenuItemCommand.Execute(selectedItem);
    }
}

In OnNavigatedTo I am guaranteed I’ll have a valid HomeViewModel from which I can navigate to our first view, Enter Time.

From EnterTimeView we can get back to our menu two different ways: 1. Press the phone Back button 2. Press the Menu icon in the ApplicationBar

Setting Up the Phone Back Button

We actually don’t have to provide any code for this functionality, this is built into Windows Phone 8.

ApplicationBar Setup

First we’ll add the code for our ApplicationBar to EnterTimeView.xaml

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton Click="ShowMenu" IconUri="/Toolkit.Content/ApplicationBar.Select.png" Text="Menu"/>           
        <shell:ApplicationBarIconButton Click="AddNewHoursEntry"  IconUri="/Assets/AppBar/add.png" Text="Add Hours"/>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem Click="ShowMenu" Text="Menu"/>                
            <shell:ApplicationBarMenuItem Click="AddNewHoursEntry" Text="Add Hours Entry"/>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Here I’ve added a second ApplicationBarIconButton and ApplicationBarMenuItem that would allow us to show another View when pressed to mimic the functionality in the iOS and Android implementations.

wp8 entertime app bar

Getting ApplicaitonBar.Select.png

ApplicationBar.Select.png is part of the Windows Phone Toolkit, add it to your project via NuGet if you’d like to use the same icon I’m using. Mark the icon as Content to ensure it is include with your application.

ShowMenu()

The ShowMenu() function uses the NavigationService allowing us to navigate back to our menu in the HomeView.

private void ShowMenu(object sender, EventArgs e)
{
    NavigationService.GoBack();
}

Conclusion

The lack of slide out menus in Windows Phone 8 shouldn’t stop us from creating a Windows Phone 8 app that uses ViewModels that were designed with the slide out menu architecture in mind. With the example code one can now create one .Core MvvmCross project based on slide out menus and use it in Windows Phone 8, iOS, and Android apps.

Grab the code and try it out: https://github.com/benhysell/V.FlyoutTest

MvvmCross – Keychain Plugin with Windows Phone 8 Silverlight Support

Summary

Unified MvvmCross Keychain Plugin for iOS, Android, and Windows Phone 8 Silverlight

Source Code

Original - https://github.com/wedkarz/IHS.MvvmCross.Plugins.Keychain Updated with Windows Phone Support - https://github.com/benhysell/IHS.MvvmCross.Plugins.Keychain

Introduction

The major app platforms, iOS, Android, and Windows Phone have mechanisms available to the app developer to store usernames and passwords. The rub is, each implementation is a bit different, and none of the major frameworks have plugins for MvvmCross.

Artur Rybak went out and created a unifying plugin for MvvmCross, IHS.MvvmCross.Plugins.Keychain. I have added onto the plugin to include support for Windows 8 Silverlight applications.

Why?

Most of the time developers would never store raw usernames and passwords in their app, one strives to store a token or hash of these sensitive items. If the device is compromised the attacker woudn’t gain a user’s raw username or password.

However, when connecting to web services often times an app developer will need the raw username and password, hence each of the major platforms provide a secure system to store these credentials.

Implementation

Artur Rybak’s plugin, IHS.MvvmCross.Plugins.Keychain covers iOS and Android with a simple interface that met all of my needs:

namespace IHS.MvvmCross.Plugins.Keychain
{
    public interface IKeychain
    {
        bool SetPassword(string password, string serviceName, string account);
        string GetPassword(string serviceName, string account);
        bool DeletePassword(string serviceName, string account);
        LoginDetails GetLoginDetails(string serviceName);
        bool DeleteAccount(string serviceName, string account);
    }
}

The implementation uses the idea of a serviceName so one can keep their usernames/passwords separate from other services on the device.

Usage

This is a great plugin because “it just works.” Need a user name and password from your MvvmCross application?

var keyChain = Mvx.Resolve<IKeychain>();
var user = keyChain.GetLoginDetails(SERVICE);

if(null != user)
    var loginResult = service.Login(user.Username, user.Password);

keyChain.GetLoginDetails(SERVICE) will return null if a username and password cannot be found for your service.

Issues

The only issue I had was on iOS, and this may have only been a simulator issue, but I found when I attempted to update a username and/or password for a service the old entries were never deleted. To work around this issue I cleared out all user names and passwords for my particular service before adding one back in.

var keyChain = Mvx.Resolve<IKeychain>();
var user = keyChain.GetLoginDetails(SERVICE);
while (user != null) //clear out old user, if we don't it will hold onto all of the old users
{
    keyChain.DeletePassword(SERVICE, user.Password);
    keyChain.DeleteAccount(SERVICE, user.Username);
    user = keyChain.GetLoginDetails(SERVICE);
}                    
keyChain.SetPassword(Password, SERVICE, Username);

Windows Phone 8 Silverlight Implementation

In iOS and Android it appears there is a single system wide service that handles storage of raw passwords and usernames, and hence the required serviceName when accessing the keychain.

In Windows Phone 8 Silverlight, this isn’t the case. The best suggestion I found for storing usernames and passwords was to place them in isolated storage. I based my implementation on an answer found on StackOverflow, Username and Password data Windows phone 8 app.

public bool SetPassword(string password, string serviceName, string account)
{
    // Convert the password to a byte[].
    var passwordByte = Encoding.UTF8.GetBytes(password);

    // Encrypt the password by using the Protect() method.
    var protectedPasswordByte = ProtectedData.Protect(passwordByte, null);

    // Store the encrypted password in isolated storage.
    WriteToFile(protectedPasswordByte, serviceName + account);

    // same steps for the username
    var usernameByte = Encoding.UTF8.GetBytes(account);
    var protectedUsernameByte = ProtectedData.Protect(usernameByte, null);
    WriteToFile(protectedUsernameByte, serviceName);

    return true;
}

/// <summary>
/// Write a string to isolated storage
/// </summary>
/// <param name="data"></param>
/// <param name="filePath"></param>
private void WriteToFile(byte[] data, string filePath)
{
    // Create a file in the application's isolated storage.
    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream writestream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, file);

    // Write pinData to the file.
    Stream writer = new StreamWriter(writestream).BaseStream;
    writer.Write(data, 0, data.Length);
    writer.Close();
    writestream.Close();
}

Since we are storing files to isolated storage I named the password file serviceName + account and the username file just serviceName.

Obtaining a username and password requires one to read the files from isolated storage:

public string GetPassword(string serviceName, string account)
{            
    return ReadIsolatedStorage(serviceName+account);
}

public string GetUsername(string serviceName)
{
    return ReadIsolatedStorage(serviceName);
}

/// <summary>
/// Given a filename read the item from isolated storage
/// </summary>
/// <param name="filename">defines item developer is looking for in isolated storage</param>
/// <returns>value found in isolated storage</returns>
private string ReadIsolatedStorage(string filename)
{
    using (var folder = IsolatedStorageFile.GetUserStoreForApplication())
    {
        string returnValue = null; //null if not found
        if (folder.FileExists(filename))
        {
            // Retrieve the item from isolated storage.
            byte[] protectedItemByte = this.ReadFromFile(filename);

            // Decrypt the item by using the Unprotect method.
            byte[] itemByte = ProtectedData.Unprotect(protectedItemByte, null);

            // Convert the password from byte to string and display it in the text box.
            returnValue = Encoding.UTF8.GetString(itemByte, 0, itemByte.Length);
        }
        return returnValue;
    }
}

        
/// <summary>
/// Read value from isolated storage
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private byte[] ReadFromFile(string filePath)
{
    // Access the file in the application's isolated storage.
    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Open, FileAccess.Read, file);

    // Read the PIN from the file.
    Stream reader = new StreamReader(readstream).BaseStream;
    byte[] pinArray = new byte[reader.Length];

    reader.Read(pinArray, 0, pinArray.Length);
    reader.Close();
    readstream.Close();

    return pinArray;
}

Windows Phone 8.1

Windows Phone 8.1 supports the Credential Locker. Once Windows Phone 8.1 is released I’ll update the library accordingly.

MvvmCross Plugin

Creating a plugin for MvvmCross was straightforward, I followed the path set by Artur Rybak, I added a KeychainPluginBootstrap.cs.pp and modified the IHS.MvvmCross.Plugins.Keychain.nuspec so the Windows Phone implementation was included in the NuGet package.

Using My Branch in a MvvmCross Application

IHS.MvvmCross.Plugins.Keychain is published on NuGet. As of publishing this blog post I have submitted a pull request to Artur Rybak to include my latest changes. If you are impatient for an ‘official release’ here are the steps you’ll need to take to get the plugin installed in your MvvmCross application.

  1. Pull down a copy of https://github.com/benhysell/IHS.MvvmCross.Plugins.Keychain
  2. Build
  3. Drop to the command line and navigate to the common folder of IHS.MvvmCross.Plugins.Keychain.
  4. Package the plugin - nuget pack IHS.MvvmCross.Plugins.Keychain.nuspec, one should now have a new NuGet package with the Keychain plugin for iOS, Android, and Windows Phone.
  5. Open your MvvmCross project and setup Visual Studio to have a new, local NuGet repository. Tools\Options\NuGetPackage Manager\Package Sources
  6. Add the directory where you just built the NuGet Packages. I called my new local location Keychain. Screen Shot 2014-06-22 at 1.57.12 PM
  7. Open your MvvmCross application, Manage NuGet Packages and select the keychain package from your new local NuGet repository. Screen Shot 2014-06-22 at 1.58.45 PM

Conclusion

If one must store username’s and passwords locally on the device ensure you are using a built in mechanism to do so, attempting to create your own password store is a difficult path I do not recommend. https://github.com/benhysell/IHS.MvvmCross.Plugins.Keychain provides a plugin for MvvmCross to work with iOS, Android, and Windows Phone.

MvvmCross – Xamarin.Android Popup DatePicker on EditText Click

Goal

When the user clicks on an EditText box in a MvvmCross Xamarin.Android app show a date picker popup.

Screenshot_2014-04-24-15-09-55

Research

Solution

All of the solutions I kept finding to this problem always had the user clicking on a button to show the DatePicker popup, and I really wanted the user to be able to show the date picker when they pressed on the EditText box, much like Android does in the default Calendar app.

From the above articles I was able to piece together a solution, the highlights:

  • Instead of setting the click event on a button set it to the EditText box.
datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);            
datePickerText.Click += delegate
{
    var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
    dialog.Show(FragmentManager, "date");
};
  • Ensure when the user presses on the EditText box that the system does not display the default keyboard by setting datePickerText.Focusable = false;.

  • For MvvmCross binding we only need to bind to the datePickerText.

The full solution:

public class EnterTimeView : MvxFragment, DatePickerDialog.IOnDateSetListener
{
    private EditText datePickerText;
    
    public EnterTimeView()
    {
        this.RetainInstance = true;
    }

    public override Android.Views.View OnCreateView(Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
    {
        this.HasOptionsMenu = true;
          
        var ignored = base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Layout.EnterTimeView, container, false);

        datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);
        datePickerText.Focusable = false;
        datePickerText.Click += delegate
        {
            var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
            dialog.Show(FragmentManager, "date");
        };

        var set = this.CreateBindingSet<EnterTimeView, EnterTimeViewModel>();
        set.Bind(datePickerText).To(vm => vm.Date);
        set.Apply();

        return view;
    }
             
    public void OnDateSet(Android.Widget.DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString();
    }

    private class DatePickerDialogFragment : Android.Support.V4.App.DialogFragment 
    {
        private readonly Context _context;
        private DateTime _date;
        private readonly DatePickerDialog.IOnDateSetListener _listener;

        public DatePickerDialogFragment(Context context, DateTime date, DatePickerDialog.IOnDateSetListener listener)
        {
            _context = context;
            _date = date;
            _listener = listener;
        }

        public override Dialog OnCreateDialog(Bundle savedState)
        {
            var dialog = new DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
            return dialog;
        }
    }
}

MvvmCross – Custom MvxTableViewCell Without a NIB File

Summary

Programmatically create a custom MvxTableViewCell without using a NIB file.

Source Code

https://github.com/benhysell/V.MvvmCross.CustomCell

Research

Introduction

As I venture deeper into MvvmCross based development I had a need to create a custom MvxTableViewCell without using a NIB file. There are several examples of how one can use a NIB file to complete this task, but as a general rule I try to stay away from NIB files and choose to create all of my iOS interfaces in code.

Problem Domain

I’m working on a application that allows an engineer to track their time spent against all the projects they are working on. My example user interface for this demo has a calendar with a UIDatePicker allowing the engineer to select the date and then show all of the entries they have made for that date.

iOS Simulator Screen shot Apr 16, 2014, 3.43.25 PM

My data source for this example is a simple class containing the job name, a job id, and the number of hours spent on that job: public class EnterTime { public string JobName { get; set; } public string JobId { get; set; } public decimal Hours { get; set; } }

Attempting to display all three elements in a standard MvxTableViewCell wasn’t working, thus the need for a custom cell.

View and ViewModel

FirstView and FirstViewModel are standard MvvmCross Views and ViewModels…no real magic needs to take place in these for us to use a custom cell. In this example code FirstViewModel provides functionality that simulates an async server call to retrieve data for a given date provided by the user. FirstViewModel is also setup for pull to refresh, delete, and select from the UITableView. Thanks again goes to James Montemagno for two great Gists to make pull to refresh and swipe to delete happen:

MvxDeleteTableViewSource

I used James Montemagno’s MvvmCross TableView Swipe to Delete as a starting point for my TableViewSource and proceeded with a few key modifications.

Register Our Custom Cell Class

In the constructor we need to tell the UITableView which class we will be using for our cells, this is done via RegisterClassForCellReuse.

private IRemove viewModel;        

public MvxDeleteTableViewSource(IRemove viewModel, UITableView tableView) : base(tableView)
{
    this.viewModel = viewModel;
    tableView.RegisterClassForCellReuse(typeof(HoursEntryCell), new NSString("HoursEntryCell"));
}

Derive From MvxTableViewSource

Originally MvxDeleteTableViewSource derived from MvxStandardTableViewSource, this however caused issues with data binding failing to work for my custom cell. Deriving from MvxTableViewSource and implementing GetOrCreateCellFor solved the data binding issues.

protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
{
    return (HoursEntryCell)tableView.DequeueReusableCell("HoursEntryCell");
}

Custom MvxTableViewCell

The HoursEntryCell turned out to be straight forward…in each constructor call CreateLayout and ensure data binding is initialized.

[Register("HoursEntryCell")]
public class HoursEntryCell : MvxTableViewCell
{        
    public HoursEntryCell()            
    {
        CreateLayout();
        InitializeBindings();
    }

    public HoursEntryCell(IntPtr handle) : base(handle)
    {
        CreateLayout();
        InitializeBindings();
    }

    private UILabel jobId;
    private UILabel hours;
    private UILabel jobName;
       
    private void CreateLayout()
    {
        const int offsetStart = 10;
        Accessory = UITableViewCellAccessory.DisclosureIndicator;
        jobId = new UILabel(new RectangleF(offsetStart, 0, 75, 40));
        hours = new UILabel(new RectangleF(UIScreen.MainScreen.Bounds.Right - 85, 0, 55, 40));
        hours.TextAlignment = UITextAlignment.Right;
        jobName = new UILabel(new RectangleF(jobId.Frame.Right, 0, UIScreen.MainScreen.Bounds.Width - jobId.Frame.Width - hours.Frame.Width - (3 * offsetStart), 40));
        jobName.AdjustsFontSizeToFitWidth = true;
        jobName.Lines = 0;
        jobName.Font = jobName.Font.WithSize(10);
        ContentView.AddSubviews(jobId, jobName, hours);
    }

    private void InitializeBindings()
    {
        this.DelayBind(() =>
        {
            var set = this.CreateBindingSet<HoursEntryCell, EnterTime>();
            set.Bind(jobId).To(vm => vm.JobId);
            set.Bind(hours).To(vm => vm.Hours);
            set.Bind(jobName).To(vm => vm.JobName);
            set.Apply();
        });
    }
}

Conclusion

The big hurtle I had with creating a custom UITableViewCell in MvvmCross without using a NIB file was deriving from the wrong MvxTableViewSource. Once I had that sorted out everything worked as expected, and I can now create my custom cells all in code without a NIB file.