检查getArguments是否有一些要检索的数据

ant*_*009 13 android

Android Studio 0.8.7
Run Code Online (Sandbox Code Playgroud)

我有以下函数在片段中设置一些参数:

 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;
    }
Run Code Online (Sandbox Code Playgroud)

在我的onCreate()中,我使用getArguments检索参数,如下所示:

@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);
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

但是,有时会出现我不会发送任何要检索的参数的情况,在这种情况下我的程序会崩溃.

使用Intents有hasExtra方法来检查:

 if(getActivity().getIntent().hasExtra(Intent.EXTRA_TEXT)) {
            /* There is something to be retrieved */
        }
Run Code Online (Sandbox Code Playgroud)

我想知道getArguments是否有类似的东西

提前谢谢了,

Squ*_*onk 21

作为对其他答案的替代建议,您的newInstance(...)方法可以设计得稍好一些.就目前而言,即使您的UUID参数是,它也总是添加参数null.

尝试将其更改为此...

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;
}
Run Code Online (Sandbox Code Playgroud)

然后在onCreate(...)你的方法Fragment之前检查参数......

Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(EXTRA_JOB_ID))
    UUID uuid = (UUID)arguments().getSerializable(EXTRA_JOB_ID);
Run Code Online (Sandbox Code Playgroud)


ρяσ*_*я K 11

Fragment.getArguments返回Bundle对象从其他组件发送的所有值.所以你可以使用Bundle.containsKey来检查密钥是否在收到的包中可用:

  Bundle bundle=getArguments();

   if(bundle !=null)
      if(bundle.containsKey(EXTRA_JOB_ID)){

            // get value from bundle..
      }
Run Code Online (Sandbox Code Playgroud)