安卓碎片 getArguments() 返回 null。

4

getArguments()返回null!

在activity中的代码:

if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            FlightListFragment listFragment = 
                     FlightListFragment.newInstance(mSearchParams);
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, listFragment).commit();
 }  

在片段中:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
                    savedInstanceState) {
        mSearchParams = 
               getArguments().getParcelable(SearchResultsActivity.EXTRA_SEARCH_PARAMS);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

并且:

public static FlightListFragment newInstance(SearchParams sp) {
    FlightListFragment f = new FlightListFragment();
    Bundle b = new Bundle();
    b.putParcelable(SearchResultsActivity.EXTRA_SEARCH_PARAMS, sp);
    f.setArguments(b);
    return f;
}

但我总是在这里遇到NullPointerException:getArguments()。
请解释一下我做错了什么。
谢谢!

编辑:
我发现newInstance()方法是在onCreateView之后调用的,所以我将代码从onCreateView移动到onCreate中,但问题没有得到解决。

1个回答

10

这意味着在创建片段时没有提供参数...

您可以通过执行以下操作来检查是否提供了参数...

Bundle arguments = getArguments();
if (arguments != null)
{
    // then you have arguments
} else {
    // no arguments supplied...
}

好的 - 我误读了你的问题...

在执行putParcelable时,sp是否为null?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接