Analysis of the causes of android.app.fragment$instantiationexception
Source: Internet
Author: User
<span id="Label3"></p><p><p><strong><span style="font-size:18px">1. Analysis of the causes of fragment$instantiationexception</span></strong></p></p><p><p>When writing code for the fragment class, Android Lint sometimes prompts the following error:</p></p><br>Avoid Not-default Constructors in Fragments:use a default constructor plus fragment$setarguments (Bundle) instead<br><br>From the Fragment documentation:<br>Every fragment must has an empty constructor and so it can is instantiated when the restoring its Activity's state. It is strongly recommended that subclasses does not has other constructors with parameters, since these constructors would n OT be called if the fragment is re-instantiated; instead, arguments can be supplied by the caller with Setarguments (Bundle) and later retrieved by the Fragment with Getarg Uments ().<br><br>Each fragment must have a parameterless construction method, so that the fragment can be instantiated when the activity resumes State. It is strongly recommended that the subclasses of fragment do not have other constructor methods, because these constructors are not called when fragment is Re-instantiated. instead, set the parameters by Setarguments (Bundle) and then get the parameters through Getarguments.<br><p><p><br></p></p><p><p>If the fragment does not have a parameterless construction method, the app will appear crash when it resumes activity, such as rotating the device.</p></p><p><p></p></p><p><p><strong>Q: Why do I have to have a non-parametric construction method, and the method with parameter construction is not called when fragment is re-instantiated?</strong></p></p><p><p>next, analyze the process of activity recovery Status.</p></p><p><p><strong>1. OnCreate (Bundle Savedinstancestate) method of activity</strong></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">package android.app;public class Activity extends Contextthemewrapper implements Layo utinflater.factory2, window.callback, keyevent.callback, oncreatecontextmenulistener, ComponentCallbacks2, Window.onwindowdismissedcallback {final Fragmentmanagerimpl mfragments = new Fragmentmanagerimpl (); protected void OnCreate (@Nullable Bundle savedinstancestate) { ... I F (savedinstancestate! = Null) { parcelable p = savedinstancestate.getparcelable ( fragments_tag); Mfragments.restoreallstate (p, mlastnonconfigurationinstances ! = null ? mLastNonConfigurationInstances.fragments:null); } Mfragments.dispatchcreate (); ... } ...} </pre></pre>When Savedinstancestate is not null, the Fragmentmanagerimpl restoreallstate is called (parcelable state, arraylist<fragment> Nonconfig) method to restore the Fragment.<p><p></p></p><p><p><strong>2. Fragmentmanagerimpl restoreallstate (parcelable state, arraylist<fragment> Nonconfig) method</strong></p></p><p><p>This method invokes Fragmentstate's instantiate (activity activity, Fragment parent) method.<br></p></p><pre name="code" class="java">Package Android.app;final class Fragmentmanagerimpl extends Fragmentmanager implements Layoutinflater.factory2 {... void Restoreallstate (parcelable state, arraylist<fragment> nonconfig) { //If there is n O saved state at all, then there can not be //any nonconfig fragments either if (state = = Null) return; fragmentmanagerstate FMS = (fragmentmana Gerstate) state; if (fms.mactive = = Null) return; ... for (int i=0; i<fms.mactive.length; i++) { &NBS P Fragmentstate fs = fms.mactive[i]; If (fs! = Null) { & nbsp Fragment f = fs.instantiate (mactivity, mparent); &NBS P If (DEbug) log.v (TAG, "restoreallstate:active #" + i + ":" + f); MACTI Ve.add (f); //now, The fragment is instantiated (or came from B eing //retained above), Clear minstance in case we end up Re-resto ring //from this fragmentstate again. & nbsp fs.minstance = null; } else { &NB Sp Mactive.add (null); if (mavailindices = = Null) { mavailindices = new arraylist<integer> () &nbs P } if (DEBUG) log.v (TAG, "restOreallstate:avail # "+ i); Mavailindices.add (i); &nbs P } ... }}</pre><strong><strong>3. Fragmentstate's Instantiate (activity activity, Fragment Parent) method</strong></strong><p><p></p></p><p><p>The fragment static Factory method instantiate (context context, String fname, @Nullable Bundle Args) will eventually be Called.<br></p></p><p><p></p></p><pre name="code" class="java">Package Android.app;final class Fragmentstate implements parcelable {... public Fragment instantiate (Activity ACTI vity, Fragment parent) {if (minstance! = Null) {return minstance; } If (marguments! = Null) {marguments.setclassloader (activity.getclassloader ()); } minstance = fragment.instantiate (activity, mclassname, marguments); If (msavedfragmentstate! = Null) {msavedfragmentstate.setclassloader (activity.getclassloader ()); Minstance.msavedfragmentstate = msavedfragmentstate; } minstance.setindex (mindex, parent); Minstance.mfromlayout = mfromlayout; minstance.mrestored = true; Minstance.mfragmentid = mfragmentid; Minstance.mcontainerid = mcontainerid; Minstance.mtag = mtag; Minstance.mretaininstance = mretaininstance; minstance.mdetached = mdetached; Minstance.mfragmentmanager = activity.mfragments; If (fragmentmaNagerimpl.debug) log.v (fragmentmanagerimpl.tag, "instantiated fragment" + minstance); Return minstance; }}</pre><p><p></p></p><p><p></p></p><pre><pre></pre></pre><strong><strong>4. Fragment Static Factory method instantiate (context context, String fname, @Nullable Bundle Args)</strong></strong><p><p></p></p><p><p>The re-instantiation of the fragment is the use of the Java reflection mechanism, and the invocation of Fragment's parameterless construction method, So this step does not invoke the other method of constructing a Parameter. If fragment does not have a parameterless construction method, clazz.newinstance () throws instantiationexecption and then prints out a common exception, "unable to instantiate Fragment "+ fname +": Make sure class name exists, are public, and have an ' + ' empty constructor That's Public.</p></p><pre name="code" class="java"></pre><p><pre name= "code" class= "java" >package Android.app;public class Fragment implements ComponentCallbacks2, oncreatecontextmenulistener {private static final arraymap<string, class<?>> SCLASSM AP = new arraymap<string, class<?>> (); public static Fragment Instantiate (context context, String fname, @Nullable Bundle Args) {try {CLASS&L t;? > clazz = Sclassmap.get (fname); if (clazz = = Null) {//Class not found in the cache, see if It's real, and try to add it cl Azz = Context.getclassloader (). loadclass (fname); If (! Fragment.class.isAssignableFrom (clazz)) {throw New instantiationexception ("Trying to instantiate a CLA SS "+ fname +" That's not a Fragment ", new classcastexception ()); } sclassmap.put (fname, clazz); } Fragment f = (Fragment) clazz.newinstance (); If (args! = Null) {args.setclassloader (f.getclass (). getclassloader ()); F.marguments = args; } return f; } catch (classnotfoundexception e) {throw new instantiationexception ("unable to instantiate fragment" + fname + ": Make sure class name exists, was public, and have a" + "empty constructor that is public ", e); } catch (java.lang.InstantiationException e) {throw new instantiationexception ("unable to instantiate fragment "+ fname +": Make sure class name exists, are public, and have an "+" empty constr Uctor That's Public ", e); } catch (illegalaccessexception e) {throw new instantiationexception ("unable to instantiate fragment" + fname + ": Make sure class name exists, was public, and have a" + "empty constructor that is public ", e); } }}</pre><p><p></p></p><strong><strong>Q: in fact, there will be another situation, the fragment has no parameter construction method, still throws the Instantiationexception. Why is that? </strong></strong><br>When your fragment is a non-static inner class, it is not possible to instantiate the fragment by using the Java reflection mechanism at this Time. In my actual project, I defined a dialogfragment as an internal class of activity, which led to this Exception. Because the instantiation of a non-static inner class object requires an instance of the subclass object, simply instantiating the non-static inner class inevitably throws Instantiationexception.<br><br><p><p>Analysis of the causes of android.app.fragment$instantiationexception</p></p></span>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service