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
Get rid of Activity
from the names of all classes that do not inherit from Activity
. For example,
IndexFragmentActivity
is not an Activity
.
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.
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.
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.