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

18 min


0

Android Tutorials : Firebase Admob Integration Tutorial


Admob is the #1 cell promoting platform to develop your app enterprise and is powered by Google’s advert know-how. You can combine AdMob in your android software and begin incomes instantly. The finest method to make use of AdMob is with Firebase, although Google Mobile Ads SDK stays obtainable as a standalone SDK which can be used to combine Admob together with your android software. Admob publishers can begin making the most of Firebase’s free and limitless analytics resolution to monetize extra intelligently, simply by linking with Firebase and importing the Firebase SDK into your android software. In this tutorial we will probably be displaying the best way to combine Admob together with your android software utilizing Firebase.

Now allow us to create an android software on which we will combine Firebase Admob to show Banner advertisements, Interstitial advertisements and Native Ads.

1. We will show a Banner advert on the backside of the exercise.
2. We will show an Interstitial advert protecting the entire display screen, as soon as the person clicks on an merchandise within the record of films.
3. We will show Native advertisements in between the record of films that are displayed in a RecyclerView.

Project on Github

The steps will probably be described in 5 detailed but easy elements.

Note : Make certain you have got the newest model of Google Play Services and Google repository put in in your Android SDK supervisor as proven under.

Part ! : Includes steps to create a brand new Android software and arrange Firebase in it.

1. Create a brand new Android Project in Android Studio. Give it a reputation and choose the Minimum SDK on which your app will run on. I selected API 16 : Android 4.1 (JELLY_BEAN).

2. When you might be prompted so as to add an exercise to your software select Blank Activity and click on on subsequent button.

3. In the following step click on on Finish and in few seconds your software ought to be loaded in Android Studio.

4. Open construct.gradle(Module:App) file of your software and add the next dependencies inside dependencies part of construct.gradle (Module:App) file.

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

5. The software requires following permissions to work. Your app won’t work until you add these permissions to your AndroidManifest.xml file.

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

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

1. The very first thing it’s essential do to get began with Firebase is, join a free account. You can use your Google account to check in to your Firebase account.

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

3. Once you might be signed in, Click on Go to your Console button in case you are not robotically redirected to your Firebase console. Click on Create New Project button in your Firebase console.

4. Now you’ll be able to see an summary of your new Firebase mission. Now click on on Add Firebase to your Android App as proven under.

5. Now it’s essential enter your software particulars (your software’s package deal identify) and likewise get SHA-1 finger print and paste it within the discipline as proven under. Check out the notice under on the best way 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 picture reveals the best way to get SHA-1 from Android Studio.

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

Note: If you neglect to position google-services.json file below app folder, you’ll get the next error once you construct your app.

7. Open the construct.gradle (Project degree) file of your android software and add classpath ‘com.google.gms:google-services:3.0.0’ within the dependencies part. Your construct.gradle (Project degree) file will look as proven under.

// Top-level construct file the place you'll be able to add configuration choices frequent to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.instruments.construct:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your software dependencies right here; they belong
        // within the particular person module construct.gradle information
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

8. Now add apply plugin: ‘com.google.gms.google-services’ on the backside of your construct.gradle (App degree) file, just under dependencies part. Also examine whether or not you have got added the next dependencies within the dependencies part of construct.gradle (App degree). Click on sync now or re-build the android software.

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

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

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

    compile 'com.android.assist:cardview-v7:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.assist: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 every of the Banner Ad, Interstitial Ad and Native Ad.

1. Visit Admob (right here) and join a brand new account utilizing your google account. Once you login to your Admob account, you can be displayed a dashboard as proven under. Click on Monetize button so as to add a brand new app to your Admob account.

2. Click on Add your app manually and provides it a reputation and choose Android platform as proven under. A brand new App will probably be created and App-Id will probably be displayed.

3. Next step is to pick out an Ad format and customizing it the best way you need. Firstly we’ll begin with choosing Banner advert format as proven under. After customizing the Banner advert, it’s essential click on on Save button. Once you click on on Save button, a brand new Ad unit will probably be created with a singular ad-unit Id. Please make a remark of this ad-unit Id similar to the Banner advert we created simply now.

4. Next step is to hyperlink your admob app with the Firebase app you have got created within the earlier step. Click on Link to Firebase button and enter the package deal identify of your android software. Click on Continue button.

5. Now choose Link to an current Firebase mission and current Firebase app possibility as proven under.

6. Now you can be proven a message indicating that your Admob app is efficiently linked together 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 choose Interstitial Ad format.

8. After customizing the Interstitial advert, it’s essential click on on Save button. Once you click on on Save button, a brand new Ad unit will probably be created with a singular ad-unit Id. Please make a remark of this ad-unit Id similar to the Interstitial advert we created simply now.

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

10. I’ve chosen the advert dimension to be Medium and a easy template having set up button. After customizing the Native advert, it’s essential click on on Save button.

11. Once you click on on Save button, a brand new Ad unit will probably be created with a singular ad-unit Id. Please make a remark of this ad-unit Id similar to the Native advert we created simply now.

12. We now have all the three Ad unit Ids required for this tutorial. Now for those who go to Monetize tab of your Admob dashboard, will probably be displayed as proven under.

Part !V : Includes creation of recent XML structure information and modification to activity_main.xml file

1. Open your activity_main.xml file and add the next code. We have a RecyclerView to carry record of films and an AdView. AdView is a category that represents the promoting banners within the Admob SDK. This is the place the banner advert from Admob will get loaded as soon as we run our software.

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

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

        <android.assist.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.assist.design.widget.AppBarLayout>

    <android.assist.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:structureManager="LinearLayoutManager"
        instruments:listitem="@layout/item_movie" />


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


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

2. Create a brand new XML structure useful resource file below res->structure folder and identify it as activity_movie_info.xml. It features a CardView and a Textview inside it. The activity_movie_info.xml file of our software has the next code in it.

<?xml model="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:instruments="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"
    instruments:context=".MovieInfoActivity">

    <android.assist.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 contentView
                android:id="@+id/tv_movie"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textual contentAppearance="@style/TextAppearance.AppCompat.Title"
                android:textColor="@android:color/black"
                android:textSize="26sp"/>

        </LinearLayout>

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

3. Create a brand new XML structure useful resource file below res->structure folder and identify it as item_movie.xml. This structure represents every merchandise in a RecyclerView. In our case it represents a single film merchandise containing an ImageView to carry the film poster, a Textual contentView to show the identify of the film, a Textual contentView to show the like rely and an ImageView to show the like image. The item_movie.xml file of our software has the next code in it.

<?xml model="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:instruments="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 contentView
        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 contentView
        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 brand new XML structure useful resource file below res->structure folder and identify it as list_item_native_ad.xml. This structure represents every merchandise in a RecyclerView.

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

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

5. At this level of time, your construct.gradle (Module:app) file would possibly appear to be under.

apply plugin: 'com.android.software'

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

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

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

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

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

6. And additionally,at this level the construct.gradle (Module:mission) file ought to appear to be under.

// Top-level construct file the place you'll be able to add configuration choices frequent to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.instruments.construct:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your software dependencies right here; they belong
        // within the particular person module construct.gradle information
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

6. Create colours.xml file within the values folder and add the next code. You can change the colours to vary the look of the appliance.

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

7. The kinds.xml file within the values folder appears like this.

<sources>

    <!-- Base software theme. -->
    <model identify="AppTheme" mother or father="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme right here. -->
        <merchandise identify="colorPrimary">@colour/colorPrimary</merchandise>
        <merchandise identify="colorPrimaryDark">@colour/colorPrimaryDark</merchandise>
        <merchandise identify="colorAccent">@colour/colorAccent</merchandise>
    </model>

    <model identify="AppTheme.NoActionBar">
        <merchandise identify="windowActionBar">false</merchandise>
        <merchandise identify="windowNoTitle">true</merchandise>
    </model>

    <model identify="AppTheme.AppBarOverlay" mother or father="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <model identify="AppTheme.PopupOverlay" mother or father="ThemeOverlay.AppCompat.Light" />

</sources>

8. The strings.xml file within the values folder appears like this. Always maintain a behavior of together with all of your string sources on this file. Replace the values of following sources with the Ad unit Ids you have got created within the earlier a part of this tutorial.

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

9. The res->drawable folder accommodates few film posters. You can obtain the film posters from the next hyperlink and paste it in res->drawable folder of your mission.

Download film posters

Part V : Includes creation of recent Java lessons and modification to EssentialActivity.java file

1. Open your EssentialActivity.java and add the next code in it. We are displaying the record of films in a RecyclerView with the assistance of an adapter class. We have loaded Banner Ads, Interstitial Ads within the EssentialActivity itself.

package deal com.androidbash.androidbashadmobfirebase;

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

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

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


public class EssentialActivity extends AppCompatActivity {

    public static closing String TEST_DEVICE_ID = "YOUR_DEVICE_ID";
    non-public AdView mBannerAd;
    non-public InterstitialAd mInterstitialAd;
    non-public RecyclerView mRecyclerView;
    non-public Toolbar mToolbar;
    non-public 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 film that will probably be added in each third place of the record
                //As Native advertisements will probably be displayed in each third place we cant have our Movies in third pos
                listOfMovies.add(i,new Movie("Thor",
                        9475, R.drawable.thorragnorak));
                //Or you'll be able to add a null worth as a substitute of dummy film
                //listOfMovies.add(i,null);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        tremendous.onCreate(savedInstanceState);
        setContentView(R.structure.activity_main);

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

        setSupportActionBar(mToolbar);

        //Populating the record of Movies
        MoviesAdapter motion picturesAdapter = new MoviesAdapter(
                this,
                listOfMovies,
                new MoviesAdapter.MovieItemClick() {
                    @Override
                    public void onMovieClick(Movie clickedMovie) {
                        clickedMovieTitle = clickedMovie.getmName();
                        if (mInterstitialAd.isLoaded()) {
                            mInterstitialAd.present();
                        } else {
                            Intent intent = new Intent(getApplicationContext(), MovieInfoActivity.class);
                            //Sending the identify of the clicked film to subsequent exercise
                            intent.putExtra("clickedMovieName", clickedMovieTitle);
                            beginActivity(intent);
                        }
                    }
                });
        mRecyclerView.setAdapter(motion picturesAdapter);

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

            @Override
            public void onAdLoaded() {

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

        //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);
                beginActivity(intent);
            }
        });

        requestNewInterstitial();
    }


    non-public void requestNewInterstitial() {
        AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(TEST_DEVICE_ID)
                .construct();
        //You can add the next code in case you are testing in an emulator
        /*AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .construct();*/
        mInterstitialAd.loadAd(advertRequest);
    }

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

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

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

Note : The earlier step has a continuing TEST_DEVICE_ID. If you might be testing on an actual gadget it’s essential get the Device ID of your telephone and substitute the worth of the sector TEST_DEVICE_ID with the ID of your telephone. You can get the Device ID of your actual gadget in the course of the first run of your app. When your software is operating, open the logcat and write “addTestDevice” filter within the search bar. It is essential because it avoids clicking on your personal advertisements which is in opposition to Admob guidelines and rules. Your Admob account will get banned for those who click on on your personal Ads. If you have got added a check gadget, then you’ll be able to check your advertisements in that check gadget with none hesitation.

Note : If you might be testing on an Emulator then you should use the follwing line which is commented within the code.

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

2. We want an adapter class to render the info in our RecyclerView. So create a brand new Java class below your package deal and identify it as MoviesAdapter.java. As we’re displaying native advertisements for each third merchandise in our RecyclerView, we have to distinguish between Native advertisements merchandise and Movie merchandise. Hence we’re utilizing 2 totally 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 a number of of three we return NativeAdViewHolder. Otherwise we return MyViewHolder.

The interface MovieItemClick allows communication between the EssentialActivity and the MoviesAdapter to obtain person generated clicks. Depending on the place of the film merchandise on which click on is made, corresponding motion related to that merchandise [as written in onMovieClick() method of MainActivity] will probably be carried out.

We wil be beginning a brand new Activity upon clicking on every Movie merchandise in our RecyclerView as written in onMovieClick() technique of the EssentialActivity.

It has the next code in it.

package deal com.androidbash.androidbashadmobfirebase;

import android.content material.Context;
import android.assist.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 contentView;

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


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


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

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

    non-public static closing int DEFAULT_VIEW_TYPE = 1;
    non-public static closing int NATIVE_AD_VIEW_TYPE = 2;

    public MoviesAdapter(Context context,
                         List<Movie> motion pictures,
                         MovieItemClick filmItemClick) {
        mContext = context;
        mItems = motion pictures;
        mItemClickListener = filmItemClick;
    }

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


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

    }

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

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

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

        Glide.with(mContext)
                .load(presentItem.getmImage())
                .centerCrop()
                .into(myViewHolder.filmImage);

    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder implements
            View.OnClickListener {
        public Textual contentView identify;
        public Textual contentView likes;
        public ImageView likeImage;
        public ImageView filmImage;

        public MyViewHolder(View merchandiseView) {
            tremendous(merchandiseView);
            likeImage=(ImageView)merchandiseView.discoverViewById(R.id.iv_like_image);
            identify = (Textual contentView) merchandiseView.discoverViewById(R.id.tv_name);
            likes = (Textual contentView) merchandiseView.discoverViewById(R.id.tv_likes);
            filmImage = (ImageView) merchandiseView.discoverViewById(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 {

        non-public closing NativeCategoricalAdView mNativeAd;

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

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

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

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

                @Override
                public void onAdOpened() {
                    tremendous.onAdOpened();
                    if (mItemClickListener != null) {
                        Log.i("AndroidBash", "onAdOpened");
                    }
                }
            });
            AdRequest advertRequest = new AdRequest.Builder()
                    .addTestDevice(EssentialActivity.TEST_DEVICE_ID)
                    .construct();
            //You can add the next code in case you are testing in an emulator
            /*AdRequest advertRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .construct();*/
            mNativeAd.loadAd(advertRequest);
        }
    }

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

3. Create a brand new Java class below your package deal and identify it as Movie.java. This is our area class which represents a Movie. Each film may have a reputation, variety of likes and a poster related to it.

package deal com.androidbash.androidbashadmobfirebase;

import android.assist.annotation.DrawableRes;


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


    public Movie(String identify, int likes,
                 @DrawableRes int mImage) {
        this.mName = identify;
        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 brand new Java class below your package deal and identify it as MovieInfoActivity.java. This is an Activity which will get opened when the person clicks on a film merchandise within the RecyclerView. It will get the identify of the film on which the person has clicked from the intent handed to it and shows it in a CardView.

package deal com.androidbash.androidbashadmobfirebase;

import android.os.Bundle;
import android.assist.v7.app.AppCompatActivity;
import android.widget.Textual contentView;

public class MovieInfoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        tremendous.onCreate(savedInstanceState);
        setContentView(R.structure.activity_movie_info);
        String clickedMovieTitle = getIntent().getStringFurther("clickedMovieName");
        Textual contentView television = (Textual contentView) discoverViewById(R.id.tv_movie);
        television.setText(clickedMovieTitle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

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

5. Add the identify of the exercise you created within the earlier step to your AndroidManifest.xml file as proven under. This is how your AndroidManifest.xml ought to have a look at the tip of this mission.

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

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

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

                <class android:identify="android.intent.category.LAUNCHER" />
            </intent-filter>
        </exercise>
        <exercise android:identify=".MovieInfoActivity"></exercise>
    </software>

</manifest>

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

You can obtain the mission from Github and check out it out by together 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 appliance works when run on an Emulator.

If you have got appreciated our tutorial, you’ll be able to assist us maintain this web site free for all Android fanatics by donating any small quantity to my PayPal account. If you have got adopted our tutorial please do tell us by commenting under. It makes us write increasingly more articles on android software growth. In case for those who get caught someplace please do remark under and tell us. We often 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.


What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win

0 Comments

Your email address will not be published. Required fields are marked *

Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Meme
Upload your own images to make custom memes
Video
Youtube, Vimeo or Vine Embeds
Audio
Soundcloud or Mixcloud Embeds
Image
Photo or GIF
Gif
GIF format