user10823919
user10823919

Reputation:

getArguments() always returns null in Fragment

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();
}

Upvotes: 3

Views: 437

Answers (1)

Zain
Zain

Reputation: 40878

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 
}

Upvotes: 6

Related Questions