2015-01-15 94 views
0

Fragment getArguments()返回空指針異常。 已經連續一天思考如何解決這段代碼,整個互聯網已經爬上尋找答案。請幫幫我。像忠實的代碼,但由於某種原因崩潰NullPointerException?Fragment getArguments()返回空指針異常

P.S.對不起,我的英語,但我想你明白我想要問。))

//片段

public static AppsManagerFragment userFragList(int a){ 
    AppsManagerFragment f = new AppsManagerFragment(); 
    Bundle bundle = new Bundle(); 
    bundle.putInt("secretKey", a); 
    f.setArguments(bundle); 
    return f; 

}; 

public static AppsManagerFragment systemFragList(int a){ 
    AppsManagerFragment f = new AppsManagerFragment(); 
    Bundle bundle = new Bundle(); 
    bundle.putInt("secretKey", a); 
    f.setArguments(bundle); 
    return f; 

}; 


int getFragmentArg() { 
    return this.getArguments().getInt("secretKey"); // here there NPE 
} 

//活動

private FragmentTabHost mTabHost; 
private DataApps dApps; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.apps_manager_activity); 
    dApps = new DataApps(this); 

    // instance initialization 
    AppsManagerFragment userFrag = AppsManagerFragment.userFragList(1); 
    AppsManagerFragment systemFrag = AppsManagerFragment.systemFragList(2); 

    mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); 
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); 

    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"), userFrag.getClass(), null); 
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"), systemFrag.getClass(), null); 
} 

回答

5

從你的代碼我可以能夠要了解您正在返回片段的靜態實例,但在getFragmentArg()方法中,您正在訪問片段的非靜態實例。其實你應該遵循findFragmentByTag()方法,然後在該實例上使用getArguments()。它會解決你的問題。