Firebase Admob Integration Tutorial on Android : Banner Ads, Native Ads & Interstitial Ads

Firebase Admob Integration Tutorial on Android  : Banner Ads, Native Ads & Interstitial Ads

Android Tutorials : Firebase Admob Integration Tutorial


Admob is the #1 cell selling platform to develop your app enterprise and is powered by Google’s advert know-how. You can mix AdMob in your android software program and start incomes immediately. The best technique to utilize AdMob is with Firebase, though Google Mobile Ads SDK stays obtainable as a standalone SDK which can be utilized to mix Admob collectively along with your android software program. Admob publishers can start benefiting from Firebase’s free and limitless analytics decision to monetize further intelligently, just by linking with Firebase and importing the Firebase SDK into your android software program. In this tutorial we’ll most likely be displaying one of the best ways to mix Admob collectively along with your android software program using Firebase.

Now enable us to create an android software program on which we’ll mix Firebase Admob to point out Banner commercials, Interstitial commercials and Native Ads.

1. We will present a Banner advert on the bottom of the train.
2. We will present an Interstitial advert defending the complete show display screen, as quickly because the particular person clicks on an merchandise throughout the report of movies.
3. We will present Native commercials in between the report of movies which are displayed in a RecyclerView.

Project on Github

The steps will most likely be described in 5 detailed however straightforward components.

Note : Make sure you’ve got the most recent mannequin of Google Play Services and Google repository put in in your Android SDK supervisor as confirmed beneath.

Part ! : Includes steps to create a model new Android software program and organize Firebase in it.

1. Create a model new Android Project in Android Studio. Give it a repute and select the Minimum SDK on which your app will run on. I chosen API 16 : Android 4.1 (JELLY_BEAN).

2. When you is perhaps prompted in order so as to add an train to your software program choose Blank Activity and click on on on subsequent button.

3. In the next step click on on on Finish and in few seconds your software program should be loaded in Android Studio.

4. Open assemble.gradle(Module:App) file of your software program and add the following dependencies inside dependencies a part of assemble.gradle (Module:App) file.

dependencies {
    compile fileTree(dir: 'libs', embrace: ['*.jar'])
    compile 'com.android.help:appcompat-v7:25.1.0'
    compile 'com.android.help:design:25.1.0'
	
	//Firebase commercials
    compile 'com.google.firebase:firebase-ads:10.0.1'
	
	//Glide for Image Loading
    compile 'com.android.help:cardview-v7:25.1.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.help:recyclerview-v7:25.1.0'
}

5. The software program requires following permissions to work. Your app will not work till you add these permissions to your AndroidManifest.xml file.

<uses-permission android:establish = "android.permission.INTERNET" />
    <uses-permission android:establish = "android.permission.ACCESS_NETWORK_STATE" />

Part !! : Includes Firebase account creation and getting google-services.json file from Firebase console

1. The very very first thing it is important do to get started with Firebase is, be part of a free account. You can use your Google account to examine in to your Firebase account.

2. After clicking on ‘Sign In with Google’, you is prone to be requested to allow the Firebase to view your Email and your elementary profile. Click on Allow button to proceed.

3. Once you is perhaps signed in, Click on Go to your Console button in case you aren’t robotically redirected to your Firebase console. Click on Create New Project button in your Firebase console.

4. Now you can see an abstract of your new Firebase mission. Now click on on on Add Firebase to your Android App as confirmed beneath.

5. Now it is important enter your software program particulars (your software program’s bundle deal establish) and likewise get SHA-1 finger print and paste it throughout the self-discipline as confirmed beneath. Check out the discover beneath on one of the best ways to get SHA-1 from Android Studio.

Click on Add App button. Upon clicking it, a file named google-services.json will get downloaded to your machine.

Note : Following image reveals one of the best ways to get SHA-1 from Android Studio.

6. Copy the google-services.json file and paste throughout the app folder of your Android software program.

Note: If you neglect to place google-services.json file under app folder, you may get the following error when you assemble your app.

7. Open the assemble.gradle (Project diploma) file of your android software program and add classpath ‘com.google.gms:google-services:3.0.0’ throughout the dependencies half. Your assemble.gradle (Project diploma) file will look as confirmed beneath.

// Top-level assemble file the place you can add configuration decisions frequent to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.devices.assemble:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your software program dependencies proper right here; they belong
        // throughout the explicit particular person module assemble.gradle info
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

8. Now add apply plugin: ‘com.google.gms.google-services’ on the bottom of your assemble.gradle (App diploma) file, just below dependencies half. Also study whether or not or not you’ve got added the following dependencies throughout the dependencies a part of assemble.gradle (App diploma). Click on sync now or re-build the android software program.

dependencies {
    compile fileTree(dir: 'libs', embrace: ['*.jar'])
    compile 'com.android.help:appcompat-v7:25.1.0'

    compile 'com.android.help:design:25.0.1'

    compile 'com.google.firebase:firebase-ads:10.0.1'

    compile 'com.android.help:cardview-v7:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.help:recyclerview-v7:25.0.1'
}
apply plugin: 'com.google.gms.google-services'

Part !!! : Linking Admob with Firebase and getting 3 Ad unit Ids corresponding to each of the Banner Ad, Interstitial Ad and Native Ad.

1. Visit Admob (proper right here) and be part of a model new account using your google account. Once you login to your Admob account, you will be displayed a dashboard as confirmed beneath. Click on Monetize button in order so as to add a model new app to your Admob account.

2. Click on Add your app manually and gives it a repute and select Android platform as confirmed beneath. A model new App will most likely be created and App-Id will most likely be displayed.

3. Next step is to pick an Ad format and customizing it one of the best ways you want. Firstly we’ll start with selecting Banner advert format as confirmed beneath. After customizing the Banner advert, it is important click on on on Save button. Once you click on on on Save button, a model new Ad unit will most likely be created with a singular ad-unit Id. Please make a note of this ad-unit Id much like the Banner advert we created merely now.

4. Next step is to hyperlink your admob app with the Firebase app you’ve got created throughout the earlier step. Click on Link to Firebase button and enter the bundle deal establish of your android software program. Click on Continue button.

5. Now select Link to an present Firebase mission and present Firebase app risk as confirmed beneath.

6. Now you will be confirmed a message indicating that your Admob app is effectively linked collectively along with your Firebase mission. Click on Done button.

7. Next step is to create an Interstitial Ad unit and customise it. Click on Create Another Ad Unit button and select Interstitial Ad format.

8. After customizing the Interstitial advert, it is important click on on on Save button. Once you click on on on Save button, a model new Ad unit will most likely be created with a singular ad-unit Id. Please make a note of this ad-unit Id much like the Interstitial advert we created merely now.

9. Next step is to create a Native Ad unit and customise it. Click on Create Another Ad Unit button and select Native Ad format.

10. I’ve chosen the advert dimension to be Medium and a straightforward template having arrange button. After customizing the Native advert, it is important click on on on Save button.

11. Once you click on on on Save button, a model new Ad unit will most likely be created with a singular ad-unit Id. Please make a note of this ad-unit Id much like the Native advert we created merely now.

12. We now have all of the three Ad unit Ids required for this tutorial. Now for individuals who go to Monetize tab of your Admob dashboard, will most likely be displayed as confirmed beneath.

Part !V : Includes creation of latest XML construction info and modification to activity_main.xml file

1. Open your activity_main.xml file and add the following code. We have a RecyclerView to hold report of movies and an AdView. AdView is a class that represents the marketing banners throughout the Admob SDK. This is the place the banner advert from Admob will get loaded as quickly as we run our software program.

<?xml mannequin="1.0" encoding="utf-8"?>
<android.help.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:commercials="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:devices="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    devices:context=".MainActivity">

    <android.help.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.help.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.help.design.widget.AppBarLayout>

    <android.help.v7.widget.RecyclerView
        android:id="@+id/list_movies"
        android:paddingTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/banner_ad"
        android:background="@android:color/white"
        app:constructionManager="LinearLayoutManager"
        devices:listitem="@layout/item_movie" />


    <com.google.android.gms.commercials.AdView
        android:id="@+id/banner_ad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        commercials:adSize="BANNER"
        commercials:advertUnitId="@string/banner_ad_unit_id" />


</android.help.design.widget.CoordinatorLayout>

2. Create a model new XML construction helpful useful resource file under res->construction folder and establish it as activity_movie_info.xml. It incorporates a CardView and a Textview inside it. The activity_movie_info.xml file of our software program has the following code in it.

<?xml mannequin="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:devices="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    devices:context=".MovieInfoActivity">

    <android.help.v7.widget.CardView
        app:contentPadding="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@color/colorCardView"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Textual content materialView
                android:id="@+id/tv_movie"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textual content materialAppearance="@style/TextAppearance.AppCompat.Title"
                android:textColor="@android:color/black"
                android:textSize="26sp"/>

        </LinearLayout>

    </android.help.v7.widget.CardView>
</RelativeLayout>

3. Create a model new XML construction helpful useful resource file under res->construction folder and establish it as item_movie.xml. This construction represents each merchandise in a RecyclerView. In our case it represents a single movie merchandise containing an ImageView to hold the movie poster, a Textual content materialView to point out the establish of the movie, a Textual content materialView to point out the like rely and an ImageView to point out the like picture. The item_movie.xml file of our software program has the following code in it.

<?xml mannequin="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:devices="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="132dp"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:paddingBottom="8dp"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="22dp">

    <Textual content materialView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/iv_movie_image"
        android:textColor="@android:color/black"
        android:textSize="18sp"/>

    <ImageView
        android:layout_marginTop="8dp"
        android:layout_toRightOf="@+id/iv_movie_image"
        android:layout_below="@+id/tv_name"
        android:layout_width="20dp"
        android:layout_alignBottom="@+id/tv_likes"
        android:layout_height="20dp"
        android:id="@+id/iv_like_image"/>

    <Textual content materialView
        android:layout_marginLeft="8dp"
        android:id="@+id/tv_likes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_name"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:layout_toRightOf="@+id/iv_like_image"
        android:textColor="@android:color/black"
        android:textSize="16sp" />


    <ImageView
        android:id="@+id/iv_movie_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="6dp"/>

</RelativeLayout>

4. Create a model new XML construction helpful useful resource file under res->construction folder and establish it as list_item_native_ad.xml. This construction represents each merchandise in a RecyclerView.

<?xml mannequin="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:commercials="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="132dp">

    <com.google.android.gms.commercials.NativeCategoricalAdView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/nativeAd"
        commercials:adSize="FULL_WIDTHx132"
        commercials:advertUnitId="@string/native_ad_unit_id"/>
</LinearLayout>

5. At this degree of time, your assemble.gradle (Module:app) file may seem like beneath.

apply plugin: 'com.android.software program'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        software programId "com.androidbash.androidbashadmobfirebase"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        launch {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.skilled'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', embrace: ['*.jar'])
    compile 'com.android.help:appcompat-v7:25.1.0'

    compile 'com.android.help:design:25.1.0'

    compile 'com.google.firebase:firebase-ads:10.0.1'

    compile 'com.android.help:cardview-v7:25.1.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.help:recyclerview-v7:25.1.0'
}
apply plugin: 'com.google.gms.google-services'

6. And moreover,at this degree the assemble.gradle (Module:mission) file should seem like beneath.

// Top-level assemble file the place you can add configuration decisions frequent to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.devices.assemble:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your software program dependencies proper right here; they belong
        // throughout the explicit particular person module assemble.gradle info
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

6. Create colors.xml file throughout the values folder and add the following code. You can change the colors to differ the look of the equipment.

<?xml mannequin="1.0" encoding="utf-8"?>
<sources>
    <color establish="colorPrimary">#3F51B5</color>
    <color establish="colorPrimaryDark">#303F9F</color>
    <color establish="colorAccent">#FF4081</color>
    <color establish="colorCardView">#9cabf7</color>
</sources>

7. The sorts.xml file throughout the values folder seems like this.

<sources>

    <!-- Base software program theme. -->
    <mannequin establish="AppTheme" mom or father="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme proper right here. -->
        <merchandise establish="colorPrimary">@color/colorPrimary</merchandise>
        <merchandise establish="colorPrimaryDark">@color/colorPrimaryDark</merchandise>
        <merchandise establish="colorAccent">@color/colorAccent</merchandise>
    </mannequin>

    <mannequin establish="AppTheme.NoActionBar">
        <merchandise establish="windowActionBar">false</merchandise>
        <merchandise establish="windowNoTitle">true</merchandise>
    </mannequin>

    <mannequin establish="AppTheme.AppBarOverlay" mom or father="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <mannequin establish="AppTheme.PopupOverlay" mom or father="ThemeOverlay.AppCompat.Light" />

</sources>

8. The strings.xml file throughout the values folder seems like this. Always preserve a habits of along with your whole string sources on this file. Replace the values of following sources with the Ad unit Ids you’ve got created throughout the earlier part of this tutorial.

<sources>
    <string establish="app_name">AndroidBashAdmobFirebase</string>
    <string establish="banner_ad_unit_id">YOUR_BANNER_AD_UNIT_ID_HERE</string>
    <string establish="interstitial_ad_unit_id">YOUR_INTERSTITIAL_AD_UNIT_ID_HERE</string>
    <string establish="native_ad_unit_id">YOUR_NATIVE_AD_UNIT_ID_HERE</string>
</sources>

9. The res->drawable folder accommodates few movie posters. You can get hold of the movie posters from the following hyperlink and paste it in res->drawable folder of your mission.

Download movie posters

Part V : Includes creation of latest Java classes and modification to ImportantActivity.java file

1. Open your ImportantActivity.java and add the following code in it. We are displaying the report of movies in a RecyclerView with the help of an adapter class. We have loaded Banner Ads, Interstitial Ads throughout the ImportantActivity itself.

bundle deal com.androidbash.androidbashadmobfirebase;

import android.content material materials.Intent;
import android.os.Bundle;
import android.help.v7.app.AppCompatActivity;
import android.help.v7.widget.RecyclerView;
import android.help.v7.widget.Toolbar;
import android.widget.Toast;

import com.google.android.gms.commercials.AdListener;
import com.google.android.gms.commercials.AdRequest;
import com.google.android.gms.commercials.AdView;
import com.google.android.gms.commercials.InterstitialAd;

import java.util.ArrayList;
import java.util.List;


public class ImportantActivity extends AppCompatActivity {

    public static closing String TEST_DEVICE_ID = "YOUR_DEVICE_ID";
    personal AdView mBannerAd;
    personal InterstitialAd mInterstitialAd;
    personal RecyclerView mRecyclerView;
    personal Toolbar mToolbar;
    personal String clickedMovieTitle;

    public static List<Movie> listOfMovies = new ArrayList<>();

    static {
        listOfMovies.add(new Movie("Avatar 2",
                4252, R.drawable.avatar2));
        listOfMovies.add(new Movie("Power Rangers",
                9993, R.drawable.powerrangers));
        listOfMovies.add(new Movie("Beauty and the Beast",
                9654, R.drawable.beautyandthebeast));
        listOfMovies.add(new Movie("World War Z 2",
                1244, R.drawable.worldwarz2));
        listOfMovies.add(new Movie("Fate of the Furious",
                6324, R.drawable.fastandfurious));
        listOfMovies.add(new Movie("Fifty Shades Darker",
                4574, R.drawable.fiftyshadesdarker));
        listOfMovies.add(new Movie("Pirates of the Carribean",
                2542, R.drawable.pirates));
        listOfMovies.add(new Movie("Smurfs",
                6412, R.drawable.smurfs));
        listOfMovies.add(new Movie("Logan",
                3647, R.drawable.logan));
        listOfMovies.add(new Movie("Transformers",
                9475, R.drawable.transformers));
        listOfMovies.add(new Movie("Thor",
                9475, R.drawable.thorragnorak));
        listOfMovies.add(new Movie("Maze Runner Death Cure",
                9475, R.drawable.mazerunnerdeathcure));
        listOfMovies.add(new Movie("Spider Man Home Coming",
                9475, R.drawable.spidermanhomecoming));

        for(int i=0; i < listOfMovies.dimension(); i++){
            if(i>0 && ipercent3==0){
                //This is dummy movie that may most likely be added in every third place of the report
                //As Native commercials will most likely be displayed in every third place we cant have our Movies in third pos
                listOfMovies.add(i,new Movie("Thor",
                        9475, R.drawable.thorragnorak));
                //Or you can add a null value in its place of dummy movie
                //listOfMovies.add(i,null);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        large.onCreate(savedInstanceState);
        setContentView(R.construction.activity_main);

        mToolbar = (Toolbar) uncoverViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) uncoverViewById(R.id.list_movies);
        mBannerAd = (AdView) uncoverViewById(R.id.banner_ad);
        mInterstitialAd = new InterstitialAd(this);

        setSupportActionBar(mToolbar);

        //Populating the report of Movies
        MoviesAdapter movement photosAdapter = new MoviesAdapter(
                this,
                listOfMovies,
                new MoviesAdapter.MovieItemClick() {
                    @Override
                    public void onMovieClick(Movie clickedMovie) {
                        clickedMovieTitle = clickedMovie.getmName();
                        if (mInterstitialAd.isLoaded()) {
                            mInterstitialAd.current();
                        } else {
                            Intent intent = new Intent(getApplicationContext(), MovieInfoActivity.class);
                            //Sending the establish of the clicked movie to subsequent train
                            intent.putExtra("clickedMovieName", clickedMovieTitle);
                            startActivity(intent);
                        }
                    }
                });
        mRecyclerView.setAdapter(movement photosAdapter);

        //Banner Ad Request
        //Add the following code in case you might be testing on an precise gadget
        AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(TEST_DEVICE_ID)
                .assemble();
        //You can add the following code in case you might be testing in an emulator
        /*AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .assemble();*/
        mBannerAd.loadAd(advertRequest);
        mBannerAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                Toast.makeText(getApplicationContext(), "Closing the Banner Ad", Toast.LENGTH_LONG).current();
            }

            @Override
            public void onAdLoaded() {

                Toast.makeText(getApplicationContext(), "Banner Ad is loaded", Toast.LENGTH_LONG).current();
            }
        });

        //Interstitial Ad Request
        mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
                Intent intent = new Intent(getApplicationContext(), MovieInfoActivity.class);
                intent.putExtra("clickedMovieName", clickedMovieTitle);
                startActivity(intent);
            }
        });

        requestNewInterstitial();
    }


    personal void requestNewInterstitial() {
        AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(TEST_DEVICE_ID)
                .assemble();
        //You can add the following code in case you might be testing in an emulator
        /*AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .assemble();*/
        mInterstitialAd.loadAd(advertRequest);
    }

    @Override
    protected void onResume() {
        large.onResume();
        if (mBannerAd != null) {
            mBannerAd.resume();
        }
    }

    @Override
    protected void onPause() {
        large.onPause();
        if (mBannerAd != null) {
            mBannerAd.pause();
        }
    }

    @Override
    protected void onDestroy() {
        large.onDestroy();
        if (mBannerAd != null) {
            mBannerAd.destroy();
        }
    }
}

Note : The earlier step has a seamless TEST_DEVICE_ID. If you is perhaps testing on an precise gadget it is important get the Device ID of your phone and substitute the price of the sector TEST_DEVICE_ID with the ID of your phone. You can get the Device ID of your precise gadget in the midst of the primary run of your app. When your software program is working, open the logcat and write “addTestDevice” filter throughout the search bar. It is important as a result of it avoids clicking on your private commercials which is in opposition to Admob tips and guidelines. Your Admob account will get banned for individuals who click on on on your private Ads. If you’ve got added a examine gadget, then you can examine your commercials in that examine gadget with none hesitation.

Note : If you is perhaps testing on an Emulator then you need to use the follwing line which is commented throughout the code.

AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .assemble();

2. We need an adapter class to render the information in our RecyclerView. So create a model new Java class under your bundle deal and establish it as MoviesAdapter.java. As we’re displaying native commercials for every third merchandise in our RecyclerView, now we have to differentiate between Native commercials merchandise and Movie merchandise. Hence we’re using 2 completely completely different ViewHolders.

1. MyViewHolder : Each merchandise on this ViewHolder represents a Movie.
2. NativeAdViewHolder : Each merchandise on this ViewHolder represents a Native Ad.

Depending on the place of an merchandise in a RecyclerView we return the respective ViewHolder. If the place of an merchandise is quite a few of three we return NativeAdViewHolder. Otherwise we return MyViewHolder.

The interface MovieItemClick permits communication between the ImportantActivity and the MoviesAdapter to acquire particular person generated clicks. Depending on the place of the movie merchandise on which click on on is made, corresponding movement associated to that merchandise [as written in onMovieClick() method of MainActivity] will most likely be carried out.

We wil be starting a model new Activity upon clicking on each Movie merchandise in our RecyclerView as written in onMovieClick() strategy of the ImportantActivity.

It has the following code in it.

bundle deal com.androidbash.androidbashadmobfirebase;

import android.content material materials.Context;
import android.help.v7.widget.RecyclerView;
import android.util.Log;
import android.view.FormatInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Textual content materialView;

import com.bumptech.glide.Glide;
import com.google.android.gms.commercials.AdListener;
import com.google.android.gms.commercials.AdRequest;
import com.google.android.gms.commercials.NativeCategoricalAdView;


import java.util.ArrayList;
import java.util.List;


public class MoviesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    personal closing Context mContext;
    personal List<Movie> mItems = new ArrayList<>();
    personal MovieItemClick mItemClickListener;

    personal static closing int DEFAULT_VIEW_TYPE = 1;
    personal static closing int NATIVE_AD_VIEW_TYPE = 2;

    public MoviesAdapter(Context context,
                         List<Movie> movement photos,
                         MovieItemClick movieItemClick) {
        mContext = context;
        mItems = movement photos;
        mItemClickListener = movieItemClick;
    }

    @Override
    public int getItemViewSort(int place) {
        if (place>1 && place % 3 == 0) {
            return NATIVE_AD_VIEW_TYPE;
        }
        return DEFAULT_VIEW_TYPE;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup mom or father, int viewType) {
        View view;
        FormatInflater constructionInflater = FormatInflater.from(mContext);
        change (viewType) {
            default:
                view = constructionInflater
                        .inflate(R.construction.item_movie, mom or father, false);
                return new MyViewHolder(view);
            case NATIVE_AD_VIEW_TYPE:
                view = constructionInflater.inflate(R.construction.list_item_native_ad, mom or father, false);
                return new NativeAdViewHolder(view);
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int place) {
        if (!(holder instanceof MyViewHolder)) {
            return;
        }

        Movie currentItem = mItems.get(place);
        MyViewHolder myViewHolder = (MyViewHolder) holder;

        myViewHolder.establish.setText(currentItem.getmName());
        myViewHolder.likes.setText(""+currentItem.getLikes());
        myViewHolder.likeImage.setImageUseful useful resource(R.drawable.ic_favorite_black_24dp);
        myViewHolder.likeImage.setVisibility(View.VISIBLE);

        Glide.with(mContext)
                .load(currentItem.getmImage())
                .centerCrop()
                .into(myViewHolder.movieImage);

    }

    @Override
    public int getItemCount() {
        return mItems.dimension();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements
            View.OnClickListener {
        public Textual content materialView establish;
        public Textual content materialView likes;
        public ImageView likeImage;
        public ImageView movieImage;

        public MyViewHolder(View merchandiseView) {
            large(merchandiseView);
            likeImage=(ImageView)merchandiseView.uncoverViewById(R.id.iv_like_image);
            establish = (Textual content materialView) merchandiseView.uncoverViewById(R.id.tv_name);
            likes = (Textual content materialView) merchandiseView.uncoverViewById(R.id.tv_likes);
            movieImage = (ImageView) merchandiseView.uncoverViewById(R.id.iv_movie_image);
            merchandiseView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int place = getAdapterPlace();
            mItemClickListener.onMovieClick(mItems.get(place));
        }
    }

    public class NativeAdViewHolder extends RecyclerView.ViewHolder {

        personal closing NativeCategoricalAdView mNativeAd;

        public NativeAdViewHolder(View merchandiseView) {
            large(merchandiseView);
            mNativeAd = (NativeCategoricalAdView) merchandiseView.uncoverViewById(R.id.nativeAd);
            mNativeAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    large.onAdLoaded();
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdLoaded");
                    }
                }

                @Override
                public void onAdClosed() {
                    large.onAdClosed();
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdClosed");
                    }
                }

                @Override
                public void onAdFailedToLoad(int errorCode) {
                    large.onAdFailedToLoad(errorCode);
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdFailedToLoad");
                    }
                }

                @Override
                public void onAdLeftApplication() {
                    large.onAdLeftApplication();
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdLeftApplication");
                    }
                }

                @Override
                public void onAdOpened() {
                    large.onAdOpened();
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdOpened");
                    }
                }
            });
            AdRequest advertRequest = new AdRequest.Builder()
                    .addTestDevice(ImportantActivity.TEST_DEVICE_ID)
                    .assemble();
            //You can add the following code in case you might be testing in an emulator
            /*AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .assemble();*/
            mNativeAd.loadAd(advertRequest);
        }
    }

    interface MovieItemClick {
        void onMovieClick(Movie clickedMovie);
    }
}

3. Create a model new Java class under your bundle deal and establish it as Movie.java. This is our space class which represents a Movie. Each movie could have a repute, number of likes and a poster associated to it.

bundle deal com.androidbash.androidbashadmobfirebase;

import android.help.annotation.DrawableRes;


public class Movie {
    personal String mName;
    personal int likes;
    @DrawableRes
    personal int mImage;


    public Movie(String establish, int likes,
                 @DrawableRes int mImage) {
        this.mName = establish;
        this.likes = likes;
        this.mImage = mImage;
    }


    public String getmName() {
        return mName;
    }

    public void setmName(String mName) {
        this.mName = mName;
    }


    public int getLikes() {
        return likes;
    }

    public void setLikes(int likes) {
        this.likes = likes;
    }

    public int getmImage() {
        return mImage;
    }

    public void setmImage(int mImage) {
        this.mImage = mImage;
    }

}

4. Create a model new Java class under your bundle deal and establish it as MovieInfoActivity.java. This is an Activity which is able to get opened when the particular person clicks on a movie merchandise throughout the RecyclerView. It will get the establish of the movie on which the particular person has clicked from the intent handed to it and reveals it in a CardView.

bundle deal com.androidbash.androidbashadmobfirebase;

import android.os.Bundle;
import android.help.v7.app.AppCompatActivity;
import android.widget.Textual content materialView;

public class MovieInfoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        large.onCreate(savedInstanceState);
        setContentView(R.construction.activity_movie_info);
        String clickedMovieTitle = getIntent().getStringAdditional("clickedMovieName");
        Textual content materialView tv = (Textual content materialView) uncoverViewById(R.id.tv_movie);
        tv.setText(clickedMovieTitle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}

5. Add the establish of the train you created throughout the earlier step to your AndroidManifest.xml file as confirmed beneath. This is how your AndroidManifest.xml ought to take a look on the tip of this mission.

<?xml mannequin="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    bundle deal="com.androidbash.androidbashadmobfirebase">

    <uses-permission android:establish = "android.permission.INTERNET" />
    <uses-permission android:establish = "android.permission.ACCESS_NETWORK_STATE" />

    <software program
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <train
            android:establish=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <movement android:establish="android.intent.action.MAIN" />

                <class android:establish="android.intent.category.LAUNCHER" />
            </intent-filter>
        </train>
        <train android:establish=".MovieInfoActivity"></train>
    </software program>

</manifest>

Here is the last word Result of this mission as displayed on my emulator.

You can get hold of the mission from Github and take a look at it out by collectively along with your Ad unit Ids in strings.xml file of res->values folder of this mission.

Project on Github

Here is the Demo video displaying how the equipment works when run on an Emulator.

If you’ve got appreciated our tutorial, you can help us preserve this web page free for all Android fanatics by donating any small amount to my PayPal account. If you’ve got adopted our tutorial please do inform us by commenting beneath. It makes us write more and more extra articles on android software program development. In case for individuals who get caught someplace please do comment beneath and inform us. We usually reply inside a day.

Useful hyperlinks for Firebase Admob documentation

The put up Firebase Admob Integration Tutorial on Android : Banner Ads, Native Ads & Interstitial Ads appeared first on Android Bash.

CATEGORIES
TAGS
Share This

COMMENTS

Wordpress (0)