Sarthakpandit
Sarthakpandit

Reputation: 111

Integrating ad in Fragment

I want to integrate ad to my app, but the problem is that the app crashes, 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:

//it shows error in get application content and find view by id
// so I added get activity() and get view() to it

MobileAds.initialize(getActivity().getApplicationContext(), "ca-app-pub-xxxxxxxxxxxxx~33xxxxxxx");
AdView mAdView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

Upvotes: 2

Views: 3569

Answers (2)

return
return

Reputation: 1

Get the inflated view and use that as a reference to find and bind your adView

@Override
public void onStart() {
    super.onStart();
    View view = getView();
    if (view != null){
        AdView mAdView = (AdView) view.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().addTestDevice().build();
        mAdView.loadAd(adRequest);
    }
}

Upvotes: 0

Umar Ata
Umar Ata

Reputation: 4258

try this , I am supposed you placed your adView inside the xml(layout) of your fragment

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.your_fragment_layout, container, false);

 MobileAds.initialize(getActivity(), "ca-app-pub-xxxxxxxxxxxxx~33xxxxxxx");
        AdView mAdView = (AdView) v.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);


        return v;
    }

Upvotes: 5

Related Questions