Reputation: 23
Fragment getArguments()
return null pointer exception.
Already a consecutive day thinks how to fix this code, the entire Internet has climbed in search of an answer. Please help me. Code like the faithful, but for some reason crashes NullPointerException?
P.S. Sorry for my English, but I think you understand what I'm trying to ask.))
//Fragment
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
}
//Activity
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);
}
Upvotes: 1
Views: 646
Reputation: 4039
Fragment getArguments() return null pointer exception:
From your code, I can able to understand that you are returning a static instance of the fragment, but in getFragmentArg()
method you are accessing a non static instance of the fragment. Actually you should follow findFragmentByTag()
method and then use the getArguments()
on that instance. It will solve your issue.
Upvotes: 5