DailogFragment - getArguments/setArguments - why passing arguments in a bundle? - android

In the official example http://developer.android.com/reference/android/app/DialogFragment.html#BasicDialog the fragment is being created with use of static factory method that wraps arguments in a Bundle and calls no-args constructor passing args with setArguments(bundle)- so my question is - why not simply make public constructor with these arguments? What is the reason for using getArguments/setArguments fragment's methods - is maybe Dialog not guaranteed to be recreated each time, but reused? if so then when it is happening?
Thanks in advance.

Enforcing a no-arguments, default constructor pattern allows the system to re-create the fragment dynamically when necessary. From the docs:
All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
"will often" and "in some cases" leaves it vague. But short of satisfying your curiosity ... arguments it is!

Related

Why doesn't this subclass of Fragment have a empty constructor? (Google iosched)

The document of Fragment says:
All subclasses of Fragment must include a public empty constructor.
The framework will often re-instantiate a fragment class when needed,
in particular during state restore, and needs to be able to find this
constructor to instantiate it. If the empty constructor is not
available, a runtime exception will occur in some cases during state
restore.
http://developer.android.com/reference/android/app/Fragment.html
But this class doesn't have a empty constructor. Why doesn't this class have empty constructor?
https://github.com/google/iosched/blob/master/Wearable/src/main/java/com/google/samples/apps/iosched/iowear/fragments/SubmitFragment.java
Because its super class (the class it extends) has a constructor which is public, therefore it's by all the subclasses.
Because it won't be able to be easily recreated by the container in a Fragment transaction, these managed classes are encoraged to keep the default constructor. For instance, restoring the state of a fragment, which is performed automatically.
It is not forbidden by the structure, you can add other constructors if you want, for instance, for using them during Unit Tests, but ensure the keep the public default constructor available at application runtime.
Apparently, this code is wrong. But I don't know a lot about wearable-like device. Maybe the SDK work differently with wear-device.
The problem with no-empty constructor only appear when the system kill(save) an Activity and recreate it. It would like to create an instance of the Fragment but can't.

Why use newInstance for DialogFragment instead of the constructor?

Looking at the documentation of DialogFragment, one sees the static newInstance method to initialize a new alert dialog fragment. My question is, why not use a constructor to do so, like this:
public MyAlertDialogFragment(int title) {
Bundle args = new Bundle();
args.putInt("title", title);
setArguments(args);
}
Isn't this exactly the same or does it differ somehow? What's the best approach and why?
If you create a DialogFragment that receives objects through the constructor, you will have problems when android recreates your fragment.
This is what will happen:
your code creates the dialog calling the constructor you have created and passing some arguments as dependencies.
your dialog runs, and uses the dependencies that you passed though the constructor
the user closes the app
time passes, and android kills the fragment to free memory
the user opens the app again
android will recreate your dialog, this time using the default constructor. No arguments will be passed!
Your dialog will be in a undesired state. It may try to use instance variables that you expected to pass through the constructor, but as they are not there you'll get a null pointer exception.
To avoid this, you need not to rely on the constructor to establish the dependencies, but in in Bundles (arguments and saved instances). That may force you to implement Parcelable in some classes, which sucks.
EDIT: you can reproduce Android killing the app (step 4) by enabling the "don't maintain Activities" in the Development settings. That's the way to easily test it.
Android relies on Fragments having a public, zero-argument constructor so that it can recreate it at various times (e.g. configuration changes, restoring the app state after being previously killed by Android, etc.).
If you do not have such a constructor (e.g. the one in the question), you will see this error when it tries to instantiate one:
Fragment$InstantiationException: Unable to instantiate fragment
make sure class name exists, is public, and has an empty constructor that is public
Arguments given to it by Fragment.setArguments(Bundle) will be saved for you and given to any new instances that are (re)created. Using a static method to create the Fragment simply provides an easy way to setup the required arguments whilst maintaining a zero-argument constructor.
If you overload the constructor with MyAlertDialogFragment(int title), the Android system may still call the default MyAlertDialogFragment() constructor if the Fragment needs to be recreated and the parameter is then not passed.
Because when android is recreating a fragment, it always uses the empty constructor, and by using newInstance() you can set data that fragment uses when recreating, for example when the screen is rotated
for example:
public static FragmentExample newInstance(Parcelable uri) {
FragmentExample fragmentExample = new FragmentExample();
Bundle bundle = new Bundle();
bundle.putParcelable("Uri", uri);
fragmentExample.setArguments(bundle);
return fragmentExample;
}

How to create a Fragment instance correctly in Android

I have seen different ways to create a Fragment. Can somebody clear me up whats the difference between the methods and what is the best way and when to use which.
new MyFragment() I myself use this, because it seemed natural to me.
MyFragment.instantiate(Context context, String fname, Bundle args) This looks like a custom static method to create a Fragment but i've never seen it used.
My.Fragment.newInstance() This one is in an Android Developer Example.
What's each options purpose?
The most difference is when to use each sample:
1- Creates a new fragment object each time called.
2- Same as calling the empty constructor, but, if you set the fragment to setRetainInstance(true), this will not work if you use the empty constructor.
3- My.Fragment.newInstance(), method to get the single instance from a static fragment, If you have a static class extending fragment, you can create a Method to return a new fragment or the current fragment, its the singleton pattern.
4- Inflate from xml, same as calling the empty contructor, the Android FrameWork take care of attachement to the view, but the instance will be kept with the hole activity lifecycle, needs more memory and cannot be reused multiple time.

Bug in the official Android Fragments training sample?

It seems to me that there must be a bug in the Android Fragments demo.
As background, Fragments are apparently sometimes instantiated by the Android OS and thus need a public no-arg constructor:
All subclasses of Fragment must include a public empty constructor.
The framework will often re-instantiate a fragment class when needed,
in particular during state restore, and needs to be able to find this
constructor to instantiate it. If the empty constructor is not
available, a runtime exception will occur in some cases during state
restore.
But the NewsReader demo from the official Android training on Fragments constructs the HeadlinesFragment class and configures it with setOnHeadlineSelectedListener(this) from NewsReaderActivity.onCreate().
If the Android OS re-instantiates this fragment, the mHeadlineSelectedListener field will be null because HeadlinesFragment doesn't save or restore its state. It can't anyhow, because I believe it's impossible to persist a reference to an Activity.
Furthermore, I noticed that the Fragment documentation states:
It is strongly recommended that subclasses do not have other
constructors with parameters, since these constructors will not be
called when the fragment is re-instantiated; instead, arguments can be
supplied by the caller with setArguments(Bundle) and later retrieved
by the Fragment with getArguments().
On the other hand, it seems they perform instantiation and configuration (sort-of) correctly in the preceding FragmentBasics example. I say "sort of" because for some reason they directly instantiate the HeadlinesFragment rather than via SupportFragmentManager, as is done in the NewsReader demo. Regardless, they don't make the apparent mistake of calling a setter in HeadlinesFragment from MainActivity, but instead let HeadlinesFragment take responsibility for finding the OnArticleSelectedListener, where it does so during onAttach().
Is this a bug in the NewsReader example or am I missing something? In the meantime, I've submitted an Android documentation issue.

What's the point of setArguments?

Hi I was looking at the following Fragments example on the android site.
http://developer.android.com/guide/components/fragments.html#Example
I would like to know why certain methods are performed.
Why for instance, in the detailsFragment is the following method performed:
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
Could you not also simply instantiate the DetailsFragment and use a setter method to set index instead. Bypassing the whole setArguments.
What's the point of using setArguments in the first place? Could you not just use setters and getters?
You can use getters and setters, but by passing in a bundle you don't need to write that code, since it's already there. Also, I believe that these arguments are automatically passed in again if the screen orientation changes, which also makes life easier.
Essentially, setArguments and getArguments is just a design pattern that Google suggests you follow:
Every fragment must have an empty constructor, so it can be
instantiated when restoring its activity's state. It is strongly
recommended that subclasses do not have other constructors with
parameters, since these constructors will not be called when the
fragment is re-instantiated; instead, arguments can be supplied by the
caller with setArguments(Bundle) and later retrieved by the Fragment
with getArguments().
http://developer.android.com/reference/android/app/Fragment.html
I take that to include setters which are needed for your Fragment to operate as well. Then again - there's nothing forcing you to do it this way, and as you know - it's not the only way things could be made to work.
Just to add to Matthew's answer: he quoted correctly that Fragments need to have an empty constructor, so that the framework can re-instantiate them when needed.
It is fine to use getters and setters, but as the framework may destroy and re-create your Fragment, you must ensure to not lose those parameters.
This must be done via Fragment.onSaveInstanceState(). The saved stated will be passed back to you as the parameter savedInstanceState in Fragment.onCreate(), Fragment.onCreateView() and several other methods.
Using Fragment.setArguments() is (in most cases, I assume) easier, at the framework will automatically preserve the arguments and thus will do most of the work for you.
Setters may be the way to go for parameters you supply to the Fragment initially and which the fragment may adjust itself over time. Dealing with the savedInstanceState alone may be easier in this case than dealing with savedInstanceState and arguments - where you have to make a decision which is the valid parameter.
public void setArguments (Bundle args)
Supply the construction arguments for this fragment. This can only be
called before the fragment has been attached to its activity; that is,
you should call it immediately after constructing the fragment. The
arguments supplied here will be retained across fragment destroy and
creation (may be the text in bold was missing from official
documentation previously)
Fragments.setArguments(Bundle args)
In addition setters can be misused. If updateSomeOtherStuff() will change some view this will crash.
public class MyFragment extends Fragment {
void setData(someData){
this.someData = someData;
updateSomeOtherStuff()
}
}
If one passing in a bundle it is not possible to misuse the setter and you will always know that this will be set within the lifecycle methods.

Categories

Resources