2012-09-20 48 views
4

getArguments()返回null!android fragments 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,但問題沒有迴避。

回答

10

當片段被實例化它的意思是沒有提供參數...

您可以檢查是否論點做這樣的事情供應...

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

行 - 我誤解你的問題...

sp null是否在您執行putParcelable的位置?

+0

不,sp只在我嘗試恢復時爲空 – rocknow