Android 捆绑 Nullpointerexception

Android Bundle Nullpointerexception

我有两个片段,我试图在它们之间传递一个整数。在第一个中,在 Fragment_1.java 我在 onCreate 中有这个:

pontszam = 12;
Fragment fragment = new Fragment_2();
Bundle bundle = new Bundle();
bundle.putInt("pont", pontszam);
fragment.setArguments(bundle);

然后在第二个片段中,在 Fragment_2.java 我在 onCreate 中有这个:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt("pont");
TextView pontjelzo = (TextView)rootView.findViewById(R.id.pontszam_2);
pontjelzo.setText(Integer.toString(myInt));

但是我在这一行得到空指针异常:

int myInt = bundle.getInt("pont");

我做错了什么?

这就是我打开第二个片段的方式:

button_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentManager fragmentManager = getFragmentManager ();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();

            fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left).replace(R.id.content_frame, new Fragment_2());
            fragmentTransaction.commit ();


        }});

您正在将第一个 Fragment 替换为 new Fragment_2,而不是 Bundle。 在 onCreate 之上声明你的 Fragment_2(全局),实例化它:

fragment = new Fragment_2();

并更改您的 replace 行:

fragmentTransaction.replace(R.id.content_frame, fragment);