0

I would like to pass some values from an activity to a fragment. Have seen a lot of answers but none resolved my issue

Activity

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

Fragment

@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: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference

problem is here: String name = (String) bundle.get("sex");

thanks!

  • Add the line where you are making the transaction. – ADM Jan 28 '18 at 15:03
  • ADM you mean that I have to make the Bundle there where i make the transaction? Cause there is not a problem in transaction. Transaction is Below – Stathis Kaplanidis Jan 28 '18 at 15:08
  • There can not be any problem in transaction . I think you missed something just add the code of Transaction . – ADM Jan 28 '18 at 15:09

2 Answers2

0
    //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);
}
0

you can get the variable from activity in fragment by`

 MainActivity ob1 = (MainActivity) getActivity();
 string var1=ob1.sex;
shubham
  • 771
  • 7
  • 18