Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 58056

What is the correct way to implement MainActivity.OnCreate with XF 1.3

$
0
0

Since upgrading to XF 1.3 I use the following pattern for my MainActivity:

[Activity (Label = "AppCreateTwice.Android.Android", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        Xamarin.Forms.Forms.Init (this, bundle);
        try {
            LoadApplication(new App()); // <- this throws System.InvalidOperationException: Can not create more than one Application instance, if OnCreate is called again
        } 
        catch (Exception ex) {
            Console.WriteLine (ex); // <- good place for a breakpoint :-)
            throw;
        }
    }
}

This seems to be inline with what others are doing. However this doesn't handle back navigation correctly, as it may instantiate the App class twice. This situation can be re-created like this:

  1. debug App,
  2. press back soft-key,
  3. press app switcher soft-key,
  4. choose app from list to have OnCreate called again,
  5. now LoadApplication(new App()) will throw exception

The stacktrace is:

    [MonoDroid] UNHANDLED EXCEPTION:
    [MonoDroid] System.InvalidOperationException: Can not create more than one Application instance.
    [MonoDroid]   at Xamarin.Forms.Application.set_Current (Xamarin.Forms.Application value) [0x00000] in <filename unknown>:0 
    [MonoDroid]   at Xamarin.Forms.Application..ctor () [0x00000] in <filename unknown>:0 
    [MonoDroid]   at AppCreateTwice.App..ctor () [0x00000] in .../AppCreateTwice/AppCreateTwice/App.cs:8 
    [MonoDroid]   at AppCreateTwice.Android.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x00011] in .../AppCreateTwice/Android/MainActivity.cs:36 

This has been tested with the newest version of XF (1.3.0.6275-pre1) on both a Moto G device and the Android player (Nexus 4), both running KitKat.

I have tried storing the created app in static variable an only creating it if, it hasn't been created before, but this will just fail in a different maner when you call LoadApplication. Also, it is not an option to not call LoadApplication, if it has already been called previously, as this will not setup the UI correctly. I assume it is not a bug, so my question is, what is the correct idiom for MainActivity.OnCreate with XF 1.3 and onwards? The current documentation is a bit lacking :-)

I have attached a sample project to to illustrate the problem, if anyone should find it useful.


Viewing all articles
Browse latest Browse all 58056

Trending Articles



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