在下面的代码中,我试图将布局中具有mainactivity
选项卡的<fragment>
的值传递给使用fragment
和setArgument()
扩展getArgument()
的另一个类。在运行应用程序时。 logcate引发NPE
。我在代码中缺少什么?
主要活动:
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment mSelectedFragment = null;
switch (v.getId()) {
case R.id.btn00:
Bundle mBundle = new Bundle();
String clicks = Integer.toString(i);
mBundle.putString("btn1_clicks", clicks);
mSelectedFragment = new Fragment00();
mSelectedFragment.setArguments(mBundle);
if (mSelectedFragment != null) {
FragmentManager mFragmentManager = getFragmentManager();
mFragmentManager.beginTransaction()
.replace(R.id.fragment00ID, mSelectedFragment).commit();
}
i ++;
break;
}
Class_extends_fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment00, null);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);
/*line 32->*/String str = getArguments().getString("btn1_clicks").toString();
mTv.setText("the Button was clicked "+str+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+getArguments().getString("btn1_clicks").toString());
}
Logcat:
05-27 13:36:14.380: E/AndroidRuntime(11609): java.lang.RuntimeException: Unable to
start activity
ComponentInfo{com.example.fragments01/com.example.fragments01.MainActivity}:
java.lang.NullPointerException
05-27 13:36:14.380: E/AndroidRuntime(11609): at
com.example.fragments01.Fragment00.onActivityCreated(Fragment00.java:32)
05-27 13:36:14.380: E/AndroidRuntime(11609): at
android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1860)
最佳答案
我认为的问题是,您正在检索getArguments()
上的onActivityCreated
,并且尚未创建捆绑包(您正在onClick
中创建它)。您应该检查getArguments()
是否返回null或从onClick
中创建捆绑包。
旧版本为:
if (getArguments() != null){
String str = getArguments().getString("btn1_clicks").toString();
}