11th October, 2022
Hi Android developer!
AdMob is one of the largest ad network that helps you monetize. You may have seen banner ads in some apps’ recyclerview. This part will show you how to display AdMob banner ads in RecyclerView.
Step 1: Get AdMob App Id and Ad Unit Id
Go to your AdMob account and get the App Id & Ad Unit Id. Here I have used the AdMob Test Ids for this tutorial.
✿ ALWAYS TEST WITH TEST ADS
Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 Sample Banner ad unit ID: ca-app-pub-3940256099942544/6300978111
⚑ APP ID & AD UNIT ID ARE TWO DIFFERENT THINGS. DO NOT GET CONFUSED ABOUT IT.
Step 2: Create New Project
Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.
Step 3: Setup AdMob Ads SDK
3.1: Add AdMob Ads SDK to the Gradle. To do this, open app level gradle and add the following dependencies.
Project ⇒ app ⇒ build.gradle
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' //AdMob Ads SDK implementation 'com.google.android.gms:play-services-ads:18.3.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'androidx.cardview:cardview:1.0.0' }
3.2: Add AdMob Ads SDK meta-data to Your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.codestringz.recyclerviewadmobbanner"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="AllowBackup,GoogleAppIndexingWarning"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--AdMob Ads SDK--> <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="@string/admob_app_id"/> </application> </manifest>
Step 4: Setup the RecyclerView
4.1: Add RecyclerView dependencies to the App Level Gradle.
Project ⇒ app ⇒ build.gradle
dependencies { implementation 'androidx.recyclerview:recyclerview:1.1.0' }
4.2: Open the activity layout and add the RecyclerView.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/myRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
4.3: Create a simple model class that represents the country and its details.
package com.codestringz.recyclerviewadmobbanner; public class Country { private String name; private String capital; private String currency; private String continent; public Country(String name, String capital, String currency, String continent) { this.name = name; this.capital = capital; this.currency = currency; this.continent = continent; } public String getName() { return name; } public String getCapital() { return capital; } public String getCurrency() { return currency; } public String getContinent() { return continent; } }
4.4: Next create a row of the RecyclerView in the layout resource directory. You have to create two layout files.
Single row for Country View: This layout will display country details in the recyclerView.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="8dp"> <TextView android:id="@+id/countryName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="18sp"/> <TextView android:id="@+id/capital" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/currency" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/continent" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Single row for Ad View: This layout will display banner ad in the recyclerView.
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/ad_card_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:orientation="vertical" card_view:cardCornerRadius="2dp" card_view:cardElevation="2dp" card_view:contentPaddingBottom="10dp" card_view:contentPaddingTop="10dp"> </androidx.cardview.widget.CardView>
4.5: Create a custom adapter and add the code below.
The Adapter is the main code of RecyclerView which has some important methods to handle RecyclerView.
package com.codestringz.recyclerviewadmobbanner; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.ads.AdView; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class MyRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int ITEM_TYPE_COUNTRY = 0; private static final int ITEM_TYPE_BANNER_AD = 1; private ArrayList<Object> mList; private MyRecyclerViewItemClickListener mItemClickListener; MyRecyclerViewAdapter(ArrayList<Object> listItems, MyRecyclerViewItemClickListener itemClickListener) { this.mList = listItems; this.mItemClickListener = itemClickListener; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case ITEM_TYPE_BANNER_AD: //Inflate ad banner container View bannerLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.banner_ad_row, parent, false); //Create View Holder MyAdViewHolder myAdViewHolder = new MyAdViewHolder(bannerLayoutView); return myAdViewHolder; case ITEM_TYPE_COUNTRY: default: //Inflate RecyclerView row View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.county_row, parent, false); //Create View Holder final MyCountryViewHolder myCountryViewHolder = new MyCountryViewHolder(view); //Item Clicks myCountryViewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mItemClickListener.onItemClicked((Country) mList.get(myCountryViewHolder.getLayoutPosition())); } }); return myCountryViewHolder; } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { int viewType = getItemViewType(position); switch (viewType) { case ITEM_TYPE_BANNER_AD: if (mList.get(position) instanceof AdView) { MyAdViewHolder bannerHolder = (MyAdViewHolder) holder; AdView adView = (AdView) mList.get(position); ViewGroup adCardView = (ViewGroup) bannerHolder.itemView; // The AdViewHolder recycled by the RecyclerView may be a different // instance than the one used previously for this position. Clear the // AdViewHolder of any subviews in case it has a different // AdView associated with it, and make sure the AdView for this position doesn't // already have a parent of a different recycled AdViewHolder. if (adCardView.getChildCount() > 0) { adCardView.removeAllViews(); } if (adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } // Add the banner ad to the ad view. adCardView.addView(adView); } break; case ITEM_TYPE_COUNTRY: default: if (mList.get(position) instanceof Country) { MyCountryViewHolder myCountryViewHolder = (MyCountryViewHolder) holder; Country country = (Country) mList.get(position); //Set Country Name myCountryViewHolder.textViewName.setText(country.getName()); //Set Capital String capital = "Capital: " + country.getCapital(); myCountryViewHolder.textViewCapital.setText(capital); //Set Currency String currency = "Currency: " + country.getCurrency(); myCountryViewHolder.textViewCurrency.setText(currency); //Set Continent String continent = "Continent: " + country.getContinent(); myCountryViewHolder.textViewContinent.setText(continent); } break; } } @Override public int getItemCount() { return mList.size(); } @Override public int getItemViewType(int position) { if (position == 0 || mList.get(position) instanceof Country) { return ITEM_TYPE_COUNTRY; } else { return (position % MainActivity.ITEMS_PER_AD == 0) ? ITEM_TYPE_BANNER_AD : ITEM_TYPE_COUNTRY; } } @Override public long getItemId(int position) { return position; } //Country View Holder class MyCountryViewHolder extends RecyclerView.ViewHolder { private TextView textViewName; private TextView textViewCapital; private TextView textViewCurrency; private TextView textViewContinent; MyCountryViewHolder(@NonNull View itemView) { super(itemView); textViewName = itemView.findViewById(R.id.countryName); textViewCapital = itemView.findViewById(R.id.capital); textViewCurrency = itemView.findViewById(R.id.currency); textViewContinent = itemView.findViewById(R.id.continent); } } //Banner Ad View Holder class MyAdViewHolder extends RecyclerView.ViewHolder { MyAdViewHolder(View itemView) { super(itemView); } } //Country Item Click Listener public interface MyRecyclerViewItemClickListener { void onItemClicked(Country country); } }
4.6: Finally, open the Activity and add a RecyclerView Reference. Create an object of recyclerView’s adapter and set it to the recyclerView. Initialize AdMob Ads. Make a list and pass it to the adapter. That’s it.
package com.codestringz.recyclerviewadmobbanner; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final int ITEMS_PER_AD = 9; private ArrayList<Object> mListItems = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initAdMobAdsSDK(); addCountriesData(); addAdMobBannerAds(); setUIRef(); loadBannerAds(); } private void initAdMobAdsSDK() { MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); } private void setUIRef() { //Reference of RecyclerView RecyclerView mRecyclerView = findViewById(R.id.myRecyclerView); //Linear Layout Manager LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); //Set Layout Manager to RecyclerView mRecyclerView.setLayoutManager(linearLayoutManager); //Create adapter MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(mListItems, new MyRecyclerViewAdapter.MyRecyclerViewItemClickListener() { //Handling clicks @Override public void onItemClicked(Country country) { Toast.makeText(MainActivity.this, country.getName(), Toast.LENGTH_SHORT).show(); } }); //Set adapter to RecyclerView mRecyclerView.setAdapter(myRecyclerViewAdapter); } private void addCountriesData() { mListItems.add(new Country("Canada", "Ottawa", "Canadian Dollar", "North America")); mListItems.add(new Country("Norway", "Oslo", "Norwegian Krone", "Europe")); mListItems.add(new Country("Malaysia", "Kuala Lumpur", "Malaysian Ringgit", "Asia")); mListItems.add(new Country("Singapore", "Singapore", "Singapore Dollar", "Asia")); mListItems.add(new Country("United States of America", "Washington, D.C.", "United States Dollar", "North America")); mListItems.add(new Country("India", "New Delhi", "Indian Rupee", "Asia")); mListItems.add(new Country("Brazil", "Brasilia", " Brazilian Real", "South America")); mListItems.add(new Country("Australia", "Canberra", "Australian Dollar", "Oceania")); mListItems.add(new Country("Russia", "Moscow", "Russian Ruble", "Europe, Asia")); mListItems.add(new Country("Japan", "Tokyo", "Japanese Yen", "Asia")); //adding extra dummy data for (int i = 0; i < 80; i++) { mListItems.add(new Country("Country" + i, "Capital" + i, "dummy", "dummy")); } } private void addAdMobBannerAds() { for (int i = ITEMS_PER_AD; i <= mListItems.size(); i += ITEMS_PER_AD) { final AdView adView = new AdView(MainActivity.this); adView.setAdSize(AdSize.BANNER); adView.setAdUnitId(getResources().getString(R.string.admob_banner_ad_id)); mListItems.add(i, adView); } loadBannerAds(); } private void loadBannerAds() { //Load the first banner ad in the items list (subsequent ads will be loaded automatically in sequence). loadBannerAd(ITEMS_PER_AD); } private void loadBannerAd(final int index) { if (index >= mListItems.size()) { return; } Object item = mListItems.get(index); if (!(item instanceof AdView)) { throw new ClassCastException("Expected item at index " + index + " to be a banner ad" + " ad."); } final AdView adView = (AdView) item; // Set an AdListener on the AdView to wait for the previous banner ad // to finish loading before loading the next ad in the items list. adView.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); // The previous banner ad loaded successfully, call this method again to // load the next ad in the items list. loadBannerAd(index + ITEMS_PER_AD); } @Override public void onAdFailedToLoad(int errorCode) { // The previous banner ad failed to load. Call this method again to load // the next ad in the items list. Log.e("MainActivity", "The previous banner ad failed to load. Attempting to" + " load the next banner ad in the items list."); loadBannerAd(index + ITEMS_PER_AD); } }); // Load the banner ad. adView.loadAd(new AdRequest.Builder().build()); } @Override protected void onResume() { for (Object item : mListItems) { if (item instanceof AdView) { AdView adView = (AdView) item; adView.resume(); } } super.onResume(); } @Override protected void onPause() { for (Object item : mListItems) { if (item instanceof AdView) { AdView adView = (AdView) item; adView.pause(); } } super.onPause(); } @Override protected void onDestroy() { for (Object item : mListItems) { if (item instanceof AdView) { AdView adView = (AdView) item; adView.destroy(); } } super.onDestroy(); } }
⚑ PLEASE READ ADMOB POLICIES AND RESTRICTIONS CAREFULLY. ADMOB ALLOWS ONLY ONE BANNER AD PER PAGE.
Happy Coding!
References:
CatsVsDogs Club
il y a 2 minutes (modifié)
Thnx,but i got this error: java.lang.ClassCastException: com.google.android.gms.ads.AdView cannot be cast to com.codestringz.recyclerviewadmobbanner.Country (i getting json data from an url using Volley)
Logcat take me to this line in MyRecyclerViewAdapter: Country country = (Country) mList.get(position);
So please help me with this, thank you bro
Hi, Thank you for asking.
You are casting AdView class to County class, that’s why you are getting this error. Could you please check the list of data in the mList by debugging the app. Place a debug point at MyRecyclerViewAdapter: Country country = (Country) mList.get(position); and check that mList.get(position) is instance of country class or AdView class.
Also check return value of the getItemViewType method.
If you are still getting the error, don’t hesitate to contact here. Thank you. Happy coding!
How to set banner ads in RecyclerView in GridLayoutManager.
I want to show Admob banner ads after 6 item in recyclerview. I have added banner after 6 item but it is not shown properly. it shows after 6 item but could not show in complete width of the mobile.
java.lang.NullPointerException: Attempt to invoke interface method ‘java.lang.Object java.util.List.get(int)’ on a null object reference
Very nice example. Thank you very much