Passing parameters from Android FragmentActivity to Fragment

后端 未结 1 1363
Happy的楠姐
Happy的楠姐 2021-01-13 23:42

When Im trying to pass a parameter from FragmentActivity to a Fragment it gives me null pointer exception in the getArguments() in the Fragment.

Here is my FragmentA

1条回答
  •  天涯浪人
    2021-01-14 00:31

    1. Get rid of Activity from the names of all classes that do not inherit from Activity. For example, IndexFragmentActivity is not an Activity.

    2. In onCreate() of your actual activity, you are calling findFragmentById() to retrieve a fragment, then calling newInstance() on that fragment. However, the fragment will not exist the first time onCreate() is called, and you will fail here with a NullPointerException. Please correctly handle this case.

    3. The method name newInstance in Java is most commonly associated with the factory pattern, where newInstance() is a static method used in place of a public constructor to create instances of some class. Your newInstance() method is not static. This will cause confusion for those who come after you to maintain the code.

    4. You call newInstance() in onCreate(), create the new fragment instance, and then throw it away, which is a waste of time.

    Hence, assuming that your original instance of your fragment (wherever it came from) does not have an arguments Bundle set, that would explain your NullPointerException in getSelectedIndex().

    When Im trying to pass a parameter from FragmentActivity to a Fragment

    To pass a parameter to a newly created fragment, using a static newInstance() method and the arguments Bundle to create the new fragment is perfectly reasonable.

    To pass a parameter to a fragment that already exists, simply call some setter method on that fragment.

    0 讨论(0)
提交回复
热议问题