Best Practice to Instantiate Fragments with Arguments in Android

There are some ways to instantiate and pass data to fragments in android development. However, you must be careful when you do that and you should avoid the wrong approaches while you are instantiating and passing data to fragments.

The most recommended way of instantiate fragments with arguments is to have factory methods for this task.

Also, another important topic is about how to pass data to the fragments while instantiating them. In this case it is tempting to directly access the fields of your fragment and assign their values. However, this is the wrong approach. Because when your application send back to background and the other applications require more and more memory then your application and its resources will be cleared from the memory to open up space to the new ones.

In this example, to instantiate MyFragment you need to call;

Fragment fragment = MyFragment.newInstance("Gunhan", 28);

If android decides to recreate your activity and fragment, it is going to call no-argument constructor and the system guarantees to pass the arguments bundle to it.

After that when you want to return to your application the android system will create your activity and also your fragment with the default constructor with the passed arguments bundle.

Therefore if you directly set your fields then you are gonna lose their values after recreate operation.

Update: How to use the newly instantiated Fragment in your activity?
fragment_container could be any layout in your activities main layout xml. It will attach Fragment’s layout on this container layout.
UPDATE 2: DEMONSTRATING HOW TO INSTANTIATE FRAGMENT IN FRAGMENT PAGER ADAPTER

You can find the example project on https://github.com/gunhansancar/FragmentPagerExample

  • Luke Allison

    Just wondering in what situation one would need to add this to the manifest: android:configChanges=”orientation|keyboardHidden|screenSize” . I had someone help me write an application and they felt the need to override the orientation handling but it has broken all other fragments in the app.

  • Ragtime Ragtime

    It returns Name: null and Age: 0

    • Hi Ragtime,

      Do you mind to share your code sample maybe you are missing a point.

      • Ragtime Ragtime

        I used your code, nothing different :/

        • Are you sure that you are using exactly the same for instance you should instantiate the fragment ‘Fragment fragment = MyFragment.newInstance(“Gunhan”, 28);’ this way. not like new MyFragment(). This piece of code is 100% working so you should identify what you are missing or send me a sample code so that I can find your missing piece.

          • Arnold Brady

            Code is not completed, where is the main activity code?
            where I have to type this:

            Fragment fragment = MyFragment.newInstance(“Gunhan”, 28);

            This part is missing in your tutorial.

          • @arnoldbrady:disqus hey,
            The example above is not a complete fragments tutorial. It only covers for “How to instantiate a fragment” part.

            To add fragment to an activity programatically you need to use a FragmentManager and you need to supply a container layout for this fragment.

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            Fragment fragment = MyFragment.newInstance(“Gunhan”, 28);
            fragmentTransaction.add(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

            fragment_container could be any layout in your activities main layout xml. It will attach Fragment’s layout on this container layout.

  • Olushi Luqman Opemipo

    clean and elegant solution. thanks for this

  • Drew Seta

    Hey, I did the code just like it is here but I’m using it in a viewpager. When I try to go back to the previous fragment, the app crashes. Can anyone help me with it? Also, I read that you aren’t suppose to create fragment constructors with arguments. They are suppose to have no arg constructor for a default and thats it.

    • Yep that’s right. You should not use a constructor with arguments for fragments instead use the method described in the blog post.
      For your crash, if you share the crash report etc. it might be helpful to figure out what’s wrong. Otherwise it is impossible to find the error from here.

      • Drew Seta

        Hi, thanks for the quick response. So I got the code working, however when I put it into the viewpager the text feilds are null. the code is on the following github repo. I only added the files you need to help. I can upload the full project if you need. Can you please help. I’m making an app and I can really use your help! thank you!!

        https://github.com/dpr5/Fragments/tree/master

        • Hey @disqus_qsOyn7WIb7:disqus I’ve created an example repository for you.
          I hope it will be helpful to you.
          https://github.com/gunhansancar/FragmentPagerExample

          • Drew Seta

            Hi,
            WOW! Thank you for the extra time and work you put into this. You really went above and beyond for this. I really appreciate this. I haven’t had a chance to check out the code fully but I did run it with some errors I will fix soon. I have some stuff I’ve been really busy with.

            That leads me to ask if you know any good API tutorials for Android Studio? I have a project I have to do and I need your help or anyway to get a good tutorial on this. I have most of the code written and it works with one API but not with the one I want to use. The XML is written a bit differently with the one I need to use so that’s why I can’t figure it out. Can you please help me with it?

          • Hey @disqus_qsOyn7WIb7:disqus, your question is not crystal clear but If you’re trying to integrate your Android project with a RESTful or XML backend API, then I can recommend you to take a look at http://square.github.io/okhttp/ that’s the one I use for all my projects. It can use JSON or XML without any problems. Just search for “Okhttp Xml” There should be plentiful of examples.

          • Drew Seta

            Ok so is it possible for you to review my code and tell me where I am going wrong. I think I have most of the code, 95% done, I’m just screwing up somewhere in the syntax. I think it is in the “Chat” file. I’m still learning how to parse XML API data and I think I wrote something wrong there. This code was used for another API request and it worked fine, but this one doesn’t even though I updated the get methods.

            If you have the time the github link is as follows and I uploaded only the needed files.

            https://github.com/dpr5/API-assistance/tree/master

            The API link is in the “Chat” file on there. If you can, please help me out, I would understand if you can’t, no pressure. Its for a job interview so I’m really trying my best with this.

          • The example you shared seems working fine to me. The API in the example produces JSON responses but you asked XML. If you need to convert this one to XML parser you need to add to your RetrofitBuilder the following: “.addConverterFactory(SimpleXmlConverterFactory.create(new Persister(new AnnotationStrategy())))” and in your data/model/domain object you need to mark it with “org.simpleframework.xml.Root” and “org.simpleframework.xml.Element” annotations. It’s not possible to example it in comments since it requires much more code. I would possibly prepare another article about it but it takes time to prepare a good post with good examples.

          • Drew Seta

            ok I’ll try it. I ran this code and it doesn’t produce any result in the emulator. I tried this code with another api link following a tutorial and it worked for that so I don’t know why its not working and producing an output with this new link.

          • Drew Seta

            btw, is there an email I can contact you through that will be better than this thread? I’m just an innocent indie developer trying to get a better understanding of android so any god guidance here and there will be awesome from someone with more experience. lol