片段getArguments()返回空指针异常

时间:2015-01-15 23:11:56

标签: android android-fragments

Fragment getArguments()返回空指针异常。 已经连续一天想到如何修复这个代码,整个互联网已经攀升,寻找答案。请帮我。像忠实的代码,但由于某种原因崩溃了NullPointerException?

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);
}

1 个答案:

答案 0 :(得分:5)

从您的代码中我可以理解您正在返回片段的静态实例,但是在getFragmentArg()方法中,您正在访问片段的非静态实例。实际上你应该遵循findFragmentByTag()方法,然后在该实例上使用getArguments()。它将解决您的问题。