来自扩展片段的类的getArguments()时的NPE

时间:2014-05-27 10:41:40

标签: java android android-fragments fragment

在下面的代码中,我尝试将mainactivity的布局具有<fragment>标签的值传递到使用fragmentsetArgument()扩展getArgument()的另一个类}。运行App时。 logcate抛出NPE。我在代码中缺少什么?

MainActivity:

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)

1 个答案:

答案 0 :(得分:1)

我认为问题是您正在getArguments()上检索onActivityCreated,而您尚未创建该套件(您正在onClick中创建它)。您应该检查getArguments()是否返回null或从onClick创建包。

以前的版本是:

if (getArguments() != null){
    String str = getArguments().getString("btn1_clicks").toString();
}