Android - 将数据从Activity发送到NavigationDrawerFragment

时间:2014-12-29 14:35:27

标签: android android-fragments

我想将一些活动数据发送到NavigationDrawerFragment。这是我的代码;大多数代码都是由Android Studio生成的,我添加的代码在注释中显示:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

    // my code starts
    Bundle bundle = new Bundle();
    bundle.putInt("num", 123);
    mNavigationDrawerFragment.setArguments(bundle);
    // my code ends

    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    });
    int num = getArguments().getInt("num"); // my code
    mDrawerListView.setAdapter(new ArrayAdapter<String>(
            getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1,
            new String[]{
                    getString(R.string.title_section1),
                    getString(R.string.title_section2),
                    getString(R.string.title_section3),
            }));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

当我运行应用程序时,我得到NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference。我怎么能解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

由于你的NavigationDrawerFragment在你的布局中被静态声明,所以它被实例化为Activity被布局 - 即,在调用setContentView()时 - 它的onCreateView()方法正在运行在致电setArguments()之前。此外,一旦将setArguments()附加到活动上,就不能在片段上调用{{1}},因为Fragment的静态声明会自动发生。如果要将数据传递给已经活动的Fragment,一种简单的方法是在其类中创建一个公共方法,并在初始化后在实例上调用它。