Will Xamarin Android execute OnCreateView when the IntPtr constructor is called?

I am aware of the complexity of the constructor in Xamarin Android, as explained here: No constructor was found for ... (System.IntPtr, Android.Runtime.JniHandleOwnership)

and all fragments and actions and other user views that I create in the application import this constructor.

Sometimes, however, a null reference exception is OnCreateView by the OnCreateView method. Example:

 public class TestView: Android.Support.V4.App.Fragment{ public TestClass _testClass; public TestView (TestClass testClass) { this._testClass = testClass; } public TestView(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer) { } public override Android.Views.View OnCreateView (Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState) { View view = inflater.Inflate (Resource.Layout.Fragment_TestView, container, false); _testClass.ExecuteTestMethod(); return view; } } 

This piece of code raises a null reference exception in OnCreateView , an accident. This happens very rarely and never when I create a view from the code directly and test it.

Now it’s clear that the only point in this code where an exception can be thrown is the _testClass variable. So now, obviously, my question is that the OnCreateView method also executes when the javaReference constructor is javaReference ?

+7
android c # xamarin xamarin.android
source share
1 answer

Even in Java, onCreateView can be called in situations where the constructor won't, that the fragment life cycle works:

Fragment Life Cycle Diagram


Your constructor is called before the fragment is added, but your _testClass instance _testClass not always set, because Android will call the default constructor when it is restored. I would suggest that your crashes happen when you rotate the device (three times in a row?) And / or when you switch to another application and return

You need to manage this by storing the arguments (basic data types supported by the Bundle ) needed to instantiate the TestClass with onSaveInstanceState , and then use them to instantiate the TestClass in onResume

+3
source share

All Articles