Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

android - 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();
}
question from:https://stackoverflow.com/questions/65545655/getarguments-always-returns-null-in-fragment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...