getArguments() always returns null in Fragment

Viewed 136

I need to pass arguments to my fragments but getArguments() alway returns null

    public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
    PersonFragment personFragment = new PersonFragment();
    Bundle args = new Bundle();
    args.putSerializable("persList",personenListe);
    args.putInt(ARG_COLUMN_COUNT, columnCount);
    personFragment.setArguments(args);
    return new PersonFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {                              //getAguments() == null !!
        mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        mPersonenListe = (ArrayList<Person>) getArguments().getSerializable("persList");
    }
}

I'm calling it in MainActivity

openFragment(PersonFragment.newInstance(personenListe.size(), personenListe));

With this method

public void openFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}
1 Answers

Instead of returning the fragment that you set the arguments to, you returned a brand new fragment.

So change the newInstance to:

public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
    PersonFragment personFragment = new PersonFragment();
    Bundle args = new Bundle();
    args.putSerializable("persList",personenListe);
    args.putInt(ARG_COLUMN_COUNT, columnCount);
    personFragment.setArguments(args);
   //  return new PersonFragment();
    return personFragment ; // <<< change here 
}
Related