Will Xamarin Android execute OnCreateView when the IntPtr constructor is called?
I am aware of the constructor difficulty in Xamarin Android as is explained here : No constructor found for ... (System.IntPtr, Android.Runtime.JniHandleOwnership)
and all the fragments & activities & other custom views that I create in the app import this constructor.
Sometimes however a null reference exception
is thrown in 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 throws a null reference exception
in the OnCreateView
, occassionaly. This happens very rarely and never when I create the view from code directly and test it then.
Now clearly the only point in this code where the exception can be thrown is on the _testClass
variable. So now obviously my question is, is the OncreateView
method also executed when the javaReference
constructor is called?
Even in Java onCreateView
can be called in situations where the constructor would not be, that's the fragment lifecycle works:
Your constructor is called before Fragment is added, but your instance variable _testClass
doesn't always get set because Android will call the default constructor when restoring it. I'd guess that your crashes are happening when you rotate the device (three times in a row?) and/or when you go to another app and come back
You need to manage that by persisting the arguments (basic data types supported by Bundle
) needed to create an instance of TestClass
with onSaveInstanceState
, then using them to create an instance of TestClass
in onResume
上一篇: 退出,是)