I have MainActivity()
and a FirstFragment()
.
I'm calling a function which is in FirstFragment from MainActivity()
.
The problem is, that time getActivity()
returns null ?
I have MainActivity()
and a FirstFragment()
.
I'm calling a function which is in FirstFragment from MainActivity()
.
The problem is, that time getActivity()
returns null ?
Instead of using Activity reference. You can create reference of Context class.
I think you should pass
context
try like thisDo this when fragment start
mcontext will easily be casted as activity if you need it.
Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity) so if you want to use onattach you need to do
do not do
get activity will return null when you move the app to the background and return. if you use this it will just ignore this part of the code sometimes which will create bugs you won't understand where they come from.
Then in the where you want to call function in 'MainActivity' like this:
or if the fragment could belong to more than one activities, then check first:
Hope this help!
Please use
Activity
reference fromonAttach()
. I think this is the best pratice to use instance ofActivity
from Fragment