Sarthakpandit Sarthakpandit - 17 days ago 7
Android Question

integrating ad in fragment

I want to integrate ad to my app,but the problem is that the app crashes, when i add ad to an fragment instead of an activity.

can anyone tell me the working code for it.

i had tried some methods,but they didn't worked.if the code is placed in a 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);

Answer

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;
    }