【问题标题】:android fragments getArguments() return nullandroid片段getArguments()返回null
【发布时间】:2012-09-13 08:05:27
【问题描述】:

getArguments() 返回 null!

活动中的代码:

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()。
请解释一下我做错了什么。
谢谢!

已编辑:
我发现在onCreateView之后调用了newInstance()方法,所以我将代码从它移到onCreate,但问题并没有避免。

【问题讨论】:

    标签: android nullpointerexception android-fragments


    【解决方案1】:

    这意味着实例化片段时没有提供任何参数...

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

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

    好的 - 我看错了你的问题...

    在您执行 putParcelable 时 sp 是否为空?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2014-09-15
      • 2015-05-21
      相关资源
      最近更新 更多