6

there is default constructor in fragment, i want to know that what it's use and what functionality it provides? and i run the code without it it worked perfectly and i can't find any error in removing it

public class SongListFragment extends Fragment {

   private static final String SONG_IDS = "song_ids";

   // TODO: Rename and change types of parameters
   private int[] songIds;
   private OnFragmentInteractionListener mListener;

   public SongListFragment() {
      // Required empty public constructor
   }

   // TODO: Rename and change types and number of parameters
   public static SongListFragment newInstance(int[] songIds) {
      SongListFragment fragment = new SongListFragment();
      Bundle args = new Bundle();
      args.putIntArray(SONG_IDS, songIds);
      fragment.setArguments(args);
      return fragment;
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      if (getArguments() != null) {
         songIds = getArguments().getIntArray(SONG_IDS);
      }
   }

   @Override
   public View onCreateView(
      LayoutInflater inflater,
      ViewGroup      container,
      Bundle         savedInstanceState )
   {
      // Inflate the layout for this fragment
      return inflater.inflate(R.layout.fragment_song_list, container, false);
   }

   // TODO: Rename method, update argument and hook method into UI event
   public void onButtonPressed(Uri uri) {
      if (mListener != null) {
         mListener.onSongSelected(10);
      }
   }

   @Override
   public void onAttach(Context context) {
      super.onAttach(context);
      if (context instanceof OnFragmentInteractionListener) {
         mListener = (OnFragmentInteractionListener) context;
      }
      else {
         throw new RuntimeException( context.toString() +
            " must implement OnFragmentInteractionListener");
      }
   }

   @Override
   public void onDetach() {
      super.onDetach();
      mListener = null;
   }


   public interface OnFragmentInteractionListener {

      public void onSongSelected(int songId);
      }
   }
Aubin
  • 14,617
  • 9
  • 61
  • 84
hiashutoshsingh
  • 980
  • 2
  • 14
  • 41
  • 2
    It is used in the case when device has to restore the state of a fragment. No data will be passed and a default fragment will be created and then the state will be restored. Since the system has no way to know what you passed in your constructor or your newInstance, default constructor will be used and saved bundle should be passed – Kushan Feb 11 '17 at 10:32

3 Answers3

5
  • Android framework decides to recreate our fragment when the orientation changes. Android calls the no-argument constructur of our fragment. It has no idea what constructor we have created.
  • fragment.argument = bundle → in the newInstance we are passing the bundle inside it. so when we create a newInstance android will extract the bundle and store it. so when android orientation changes the android will recreates fragment using the no-arguemnt construtor and
  • can attach the bundle to the fragment as it has stored the bundle earlier. and later we can again accss that data by using getArgument like ( val video_id = argument?.getLong(EXTRA_VIDEO_ID )
  • So system restores a Fragment
  • It will automatically restore our bundle
  • Restore the state of the fragment to the same state.
Aditya Cheke
  • 53
  • 2
  • 4
3

See this question and comments / answers. In short, Fragments need to have a no-args constructor for the Android system to instantiate them (I believe the activity history manager does this, etc).

If the constructor is explicit, as in the unaltered example, then it's really there to ensure the no-args constructor works if other constructors are added, and the comment serves as a reminder (that or the original author didn't really understand the purpose and/or how the language works).

If the no-args constructor may be implicit - ie it is omitted in the source and there are no other constructors declared - then one is created behind the scenes as per the JLS (this is what happened when you deleted the constructor in your example):

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

Community
  • 1
  • 1
James Fry
  • 1,133
  • 1
  • 11
  • 28
3

It is used in the case when device has to restore the state of a fragment. No data will be passed and a default fragment will be created and then the state will be restored. Since the system has no way to know what you passed in your constructor or your newInstance, default constructor will be used and saved bundle should be passed via onCreate after the fragment is actually instantiated with the default constructor.

Kushan
  • 5,855
  • 3
  • 31
  • 45
  • Default constructor will anyway be created by java compiler if you haven't overridden any argumentated constructors in your own. – Kushan Feb 11 '17 at 10:38
  • If default constructor is created by java compiler by default, why do we need to explicitly write it? Even in the scenario you explained in answer, it should consider default constructor and not restrict developer to write it explicitly. – kAmol Mar 26 '19 at 03:53