将 activity 中的一些值传递给片段,然后传递 NullPointerException

pass some values from an activity to a fragment and then NullPointerException

我想将一些值从 activity 传递到片段。看过很多答案,但 none 解决了我的问题

Activity

Bundle bundle1 = new Bundle();
    bundle1.putString("baros",baros);
    bundle1.putString("upsos",upsos);
    bundle1.putString("sex",sex);
    CalculatorFragment calculatorFragment = new CalculatorFragment();
    calculatorFragment.setArguments(bundle1);

片段

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_calculator, container, false);

    apotelesma = view.findViewById(R.id.apotelesma);
    Bundle bundle = this.getArguments();
    String name = (String) bundle.get("sex");
    apotelesma.setText(name);
    return view;

}

java.lang.NullPointerException: 尝试在空对象引用

上调用虚拟方法'java.lang.Object android.os.Bundle.get(java.lang.String)'

问题在这里:String name = (String) bundle.get("sex");

谢谢!

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {

    }
    else if(id == R.id.firstMenu){
        fragment = new ArxikoFragment();
    }
    else if(id == R.id.calcsMenu){
         fragment = new CalculatorFragment();
    }else if(id == R.id.dietMenu){
           fragment = new DietFragment();
    }else if(id == R.id.tipsMenu){
            fragment = new TipsFragment();
    }else if(id == R.id.stoixeiaMenu){
            fragment = new StoixeiaFragment();
    }else if(id == R.id.logoutMenu){
        Intent myIntent = new Intent(StartActivity.this, MainActivity.class);
        StartActivity.this.startActivity(myIntent);
        super.onBackPressed();
    }


    if(fragment != null){
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.navigationLayout,fragment);
        fragmentTransaction.commit();
    }
    return super.onOptionsItemSelected(item);
}

你可以通过`

从片段中的activity获取变量
 MainActivity ob1 = (MainActivity) getActivity();
 string var1=ob1.sex;