Search code examples
androidlistviewadmobandroid-arrayadapteradview

ArrayAdapter with admob adview ListView Crash


IM trying to put an admob AdView into a ListView by way of an ArrayAdapter. Currently it loads fine and the ad appears as expected into the listview. When I scroll, and when the row containing the ad is out of view, the app freezes. I suppose that the removal of the adview is causing some problems. Is there a way to prevent this? Or is there a way to detect when a row is being removed from the listview? Or even better is there a way that the row does not get cleared from the listview and is retained?

here is what i have in the adapter getView Method :

public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;


    ChapterModel chapter = getItem(position);


        LinearLayout L;
        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.chapter_listview_ad, parent, false);

         }

            AdRequest request = new AdRequest();
            AdView adView;
            L=(LinearLayout) row.findViewById(R.id.chapter_row_layout);
                                        adView= new AdView((Activity) this.context,new AdSize(768,90), ADDID);


                adView.setAdListener(this);
                adView.loadAd(request);

                L.addView(adView); 
                 return row;
}

eclipse gives me: NullPopinterException in the image below enter image description here

note: this works but causes the add to be removed an reloaded every time it goes off the screen:

public int getItemViewType(int position) {
     // Don't let ListView try to reuse the views.
     return AdapterView.ITEM_VIEW_TYPE_IGNORE;
 }

Solution

  • FYI, AdMob's terms require that only 1 AdView can be present on the screen at a time, so be careful that you're not adding an AdView to every list item.

    With that said, here is a great open-source example of a ListView adapter and it's calling code that shows how to embed AdMob ads at every X items. The adapter itself is a wrapper around another adapter object, but embeds ads at a specified interval. You could pass your ArrayAdapter to this adapter, and it will put in the ads for you.