Sunday, November 15, 2015

Don't override the default constructor of a fragment.

You should not override the default empty constructors of fragments, the reason for that is framework recreates fragments accross orientation change using the deafault constructor and any initialization that you do in non default constructor will be lost

But to really experiment about what happens , try to override the constructor and cause an orientation change , you will see that most likely you will hit a null pointer exception if you have passed an object to fragment constructor and tried to access the same after orientation change

This below is an ideal way to use fragment
  /**  
    * Use this factory method to create a new instance of  
    * this fragment using the provided parameters.  
    *  
    * @param param1 Parameter 1.  
    * @return A new instance of fragment SquadFragment.  
    */  
   // TODO: Rename and change types and number of parameters  
   public static SquadFragment newInstance(String param1) {  
     SquadFragment fragment = new SquadFragment();  
     Bundle args = new Bundle();  
     args.putString(ARG_PARAM1, param1);  
     fragment.setArguments(args);  
     return fragment;  
   }  
   
   public SquadFragment() {  
     // Required empty public constructor  
   }  
   
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     if (getArguments() != null) {  
       mParam1 = getArguments().getString(ARG_PARAM1);  
     }  
     mSquadAdapter = new SquadRecyclerViewAdapter(mParam1);  
   }  

No comments:

Post a Comment