Sarthakpandit Sarthakpandit - 1 year ago 120
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(;
AdRequest adRequest = new AdRequest.Builder().build();

Answer Source

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

    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(;
        AdRequest adRequest = new AdRequest.Builder().build();

        return v;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download