I want to integrate ad to my app, but the problem is that the
MobileAds.initialize(this){ initStatus-> not work this method( onCreateView)
But I am use this method( onCreate:
MobileAds.initialize(this){ initStatus-> this working... Activity class,
But I want to use when I add ads to a fragment instead of an activity.
Can anyone tell me the working code for it?
I had tried some methods, but they didn't work. If the code is placed in an activity it works correctly
Here is the code I tried for Fragment:
CodePudding user response:
You can use this in fragment by giving the context of activity.
Update your code:-
MobileAds.initialize(this)
To:-
MobileAds.initialize(getActivity())
or you can initialize an activity variable in the fragment once the fragment is attached to the activity.
CodePudding user response:
First of all, you are using AdMob for displaying ads and that is important to mention. Second of all, the API for initializing ads can be seen here and you can see that it requires passing a Context argument and a callback:
public static void initialize (Context context,OnInitializationCompleteListener listener)
In your onCreateView method, this is a reference to the Fragment, unlike in the onCreate of the Activity where this is a reference to the Activity which acts as a context itself.
Since you have a view in your onCreateView method, you can get the context from there (reference).
You can also use the requireActivity or requireContext methods.
CodePudding user response:
this
inside Fragment will return Fragment itself so
MobileAds.initialize(requireActivity())
or MobileAds.initialize(requireContext())
DON'T USE getActivity()
IT'S NULLABLE