Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that getArguments has some data to be retrieved

Tags:

android

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,

like image 496
ant2009 Avatar asked Aug 26 '14 03:08

ant2009


1 Answers

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);
like image 112
Squonk Avatar answered Oct 24 '22 12:10

Squonk