Android Studio 0.8.7
I have the following function that sets some argument in the fragment:
public static Fragment newInstance(UUID uuid) {
Log.d(TAG, "newInstance: " + uuid);
Bundle arguments = new Bundle();
arguments.putSerializable(EXTRA_JOB_ID, uuid);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(arguments);
return fragment;
}
In my onCreate() I retrieve the arguments using getArguments like this:
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
/* Get the arguments from the fragment */
UUID uuid = (UUID)getArguments().getSerializable(EXTRA_JOB_ID);
.
.
}
However, sometimes there is a situation where I won't be sending any arguments to be retrieved, and my program will crash in that case.
Using Intents has the hasExtra method to check this:
if(getActivity().getIntent().hasExtra(Intent.EXTRA_TEXT)) {
/* There is something to be retrieved */
}
I am wondering if there is something similar with getArguments
Many thanks in advance,
As an alternative suggestion to the other answers, your newInstance(...)
method could be designed slightly better. As it stands, it always adds arguments even if your UUID
parameter is null
.
Try changing it to this...
public static Fragment newInstance(UUID uuid) {
Log.d(TAG, "newInstance: " + uuid);
DetailFragment fragment = new DetailFragment();
// Don't include arguments unless uuid != null
if (uuid != null) {
Bundle arguments = new Bundle();
arguments.putSerializable(EXTRA_JOB_ID, uuid);
fragment.setArguments(arguments);
}
return fragment;
}
Then in the onCreate(...)
method of your Fragment
check for arguments before anything else...
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(EXTRA_JOB_ID))
UUID uuid = (UUID)arguments().getSerializable(EXTRA_JOB_ID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With