'I want to integrate ad to my app, but the problem is that the ( Type mismatch. Required: Context!, Found Fragment class)
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:
Solution 1:[1]
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.
Solution 2:[2]
this
inside Fragment will return Fragment itself so
MobileAds.initialize(requireActivity())
or MobileAds.initialize(requireContext())
DON'T USE getActivity()
IT'S NULLABLE
Solution 3:[3]
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 specific listener:
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ankush Sharma |
Solution 2 | Sreehari K |
Solution 3 |