facebook native ads in listview android

Adding Facebook Native Ads in ListView – android 2016

Hey Guyz. In this post, I am going to show you how to add Facebook Native Ads on your Android Application ListView. If you are here, I believe you know what is Native Ads. If not check this link out Facebook Native ads Introduction
Facebook native ads are a good way to provide similar look and feel to the ads. I was introduced to Facebook Native ads a week ago while I was working for one of our Clients app Yoo – Free Recharge App But the issue with Facebook Native ads is Internet don’t have much Tutorials on it. So i decided to make one.

Wanted HackerKernel to work on your Dream Project – Contact Us

Facebook native ads in ListView android

Step 1. Create an app on Facebook

Follow the give steps and create an app on facebook and Note down your Placement ID Steps to create Facebook APP

Step 2. Create a new Android Studio Project

Open Android Studio and create an new Android project

Step 3. Add permissions to Mainfest

Adding internet and access network state permission in AndroidManifest.xml

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

Step 4. Adding dependency

We will be adding Volley and Facebook Audience Network dependency in order to downloading data from the web & adding Native ads

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.facebook.android:audience-network-sdk:4.+'
}

Step 5. Creating layout

We will create activity_main.xml file. This file will have a listView

activity_main.xml

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hackerkernel.fanadslistview.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list"/>
</RelativeLayout>

We will create two more Layout one for list list_row.xml and one for ads ad_list.xml

list_row.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:id="@+id/name"
            android:text="Husain"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:id="@+id/number"
            android:text="200"
            />
    
    </RelativeLayout>

ad_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ad_unit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        >

        <ImageView
            android:id="@+id/native_ad_icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            />

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

            <TextView
                android:id="@+id/native_ad_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                />

            <TextView
                android:id="@+id/native_ad_body"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="2"
                android:textColor="@android:color/black"
                android:textSize="15sp"
                />

        </LinearLayout>

    </LinearLayout>

    <com.facebook.ads.MediaView
        android:id="@+id/native_ad_media"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        >

        <TextView
            android:id="@+id/native_ad_social_context"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:ellipsize="end"
            android:lines="2"
            android:paddingRight="5dp"
            android:textColor="@android:color/black"
            android:textSize="15sp"
            />

        <Button
            android:id="@+id/native_ad_call_to_action"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:textSize="16sp"
            android:visibility="gone"
            />

    </LinearLayout>

</LinearLayout>

Step 6. Creating model class

We will create a model Class to hold data from our API

DataPojo.java

package com.hackerkernel.fanadslistview;

/**
 * Model class to hold data
 */
public class DataPojo {
    private String name;
    private String number;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

Step 7. Setting up listview

in MainActivity.java we will download data from our api, initialize ads and setup both of them in listview
http://api.hackerkernel.com/blog/ Sample api

  1. On line 61 enter your Placement ID

MainActivity.java

package com.hackerkernel.fanadslistview;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.AdSettings;
import com.facebook.ads.MediaView;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdsManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class MainActivity extends AppCompatActivity
    implements NativeAdsManager.Listener, AdListener{
    private ProgressDialog pd;
    private String url = "http://api.hackerkernel.com/blog/";
    private RequestQueue mRequestQueue;
    //list to store Data & ads (So make it and list or Object)
    private List<Object> mlist;

    private ListView listView;
    private ListViewAdapter adapter;
    private NativeAdsManager listNativeAdsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //init view
        listView = (ListView) findViewById(R.id.list);

        //init native ads manager
        listNativeAdsManager = new NativeAdsManager(this,"500269976843484_500270296843452",2);
        listNativeAdsManager.setListener(this);
        listNativeAdsManager.loadAds();

        //init progress dialog
        pd = new ProgressDialog(this);
        pd.setMessage("Please wait..");
        pd.setCancelable(true);

        //init volley
        mRequestQueue = Volley.newRequestQueue(this);

        //init list
        mlist = new ArrayList<>();

        //download data for list view
        downloadDataInBackground();
    }

    //Facebook audience network methods

    @Override
    public void onError(Ad ad, AdError adError) {
        Toast.makeText(this, "Ad failed to load: " +  adError.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAdLoaded(Ad ad) {

    }

    @Override
    public void onAdClicked(Ad ad) {
        Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
    }

    //method called when add is downloaded
    @Override
    public void onAdsLoaded() {
        //This method will download ad from FB
        //& call addNativeAd method which will add ad to listview

        NativeAd ad = this.listNativeAdsManager.nextNativeAd();
        ad.setAdListener(this);
        adapter.addNativeAd(ad);
    }

    @Override
    public void onAdError(AdError adError) {
        Toast.makeText(this, "Native ads manager failed to load: " +  adError.getErrorMessage(),
                Toast.LENGTH_SHORT).show();
    }

    /*
    * Method to download data in background
    * */
    private void downloadDataInBackground() {
        pd.show();
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                pd.dismiss();
                //parse response
                parseResponse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pd.dismiss();
                Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });
        mRequestQueue.add(request);
    }

    //Method to parse volley response
    private void parseResponse(String response) {
        try {
            JSONArray array = new JSONArray(response);
            //Loop through all the elements in an array
            for (int i = 0; i < array.length(); i++) {

                JSONObject jo = array.getJSONObject(i);
                String name = jo.getString("name");
                String number = jo.getString("number");

                //ad json parse data in DataPojo
                DataPojo current = new DataPojo();
                current.setName(name);
                current.setNumber(number);

                //add to list
                mlist.add(current);
            }

            //call method to setup listview
            setupListview();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Unable to parse json "+e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    //Method to setup list view
    private void setupListview() {
        adapter = new ListViewAdapter(this,mlist);
        listView.setAdapter(adapter);
    }

    //Adapter class for listview & ads

    private class ListViewAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private List<Object> list;

        private NativeAd ad;
        private static final int AD_INDEX = 2;
        public ListViewAdapter(Context context, List<Object> mlist) {
            this.inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
            this.list = mlist;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == AD_INDEX && ad != null){
                //return ad view
                return (View) list.get(position);
            }else {
                //add default item type to listview (Non ad)
                View view;
                if (convertView != null){
                    view = convertView;
                }else {
                    view = inflater.inflate(R.layout.list_row,parent,false);
                }

                //find view and set value
                TextView name = (TextView) view.findViewById(R.id.name);
                TextView number = (TextView) view.findViewById(R.id.number);

                //set value
                DataPojo current = (DataPojo) list.get(position);
                name.setText(current.getName());
                number.setText(current.getNumber());
                return view;
            }
        }

        public synchronized void addNativeAd(NativeAd ad) {
            if (ad == null) {
                return;
            }
            if (this.ad != null) {
                // Clean up the old ad before inserting the new one
                this.ad.unregisterView();
                this.list.remove(AD_INDEX);
                this.ad = null;
                this.notifyDataSetChanged();
            }
            this.ad = ad;
            View adView = inflater.inflate(R.layout.ad_list, null);
            inflateAd(ad, adView);
            list.add(AD_INDEX, adView);
            this.notifyDataSetChanged();
        }
    }

    //Method to inflate ads
    private void inflateAd(NativeAd nativeAd, View adView) {
        // Create native UI using the ad metadata.
        ImageView nativeAdIcon = (ImageView) adView.findViewById(R.id.native_ad_icon);
        TextView nativeAdTitle = (TextView) adView.findViewById(R.id.native_ad_title);
        TextView nativeAdBody = (TextView) adView.findViewById(R.id.native_ad_body);
        MediaView nativeAdMedia = (MediaView) adView.findViewById(R.id.native_ad_media);
        nativeAdMedia.setAutoplay(AdSettings.isVideoAutoplay());
        TextView nativeAdSocialContext =
                (TextView) adView.findViewById(R.id.native_ad_social_context);
        Button nativeAdCallToAction = (Button) adView.findViewById(R.id.native_ad_call_to_action);

        // Setting the Text
        nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
        nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
        nativeAdCallToAction.setVisibility(View.VISIBLE);
        nativeAdTitle.setText(nativeAd.getAdTitle());
        nativeAdBody.setText(nativeAd.getAdBody());

        // Downloading and setting the ad icon.
        NativeAd.Image adIcon = nativeAd.getAdIcon();
        NativeAd.downloadAndDisplayImage(adIcon, nativeAdIcon);

        // Downloading and setting the cover image.
        NativeAd.Image adCoverImage = nativeAd.getAdCoverImage();
        int bannerWidth = adCoverImage.getWidth();
        int bannerHeight = adCoverImage.getHeight();
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int mediaWidth = adView.getWidth() > 0 ? adView.getWidth() : metrics.widthPixels;
        nativeAdMedia.setLayoutParams(new LinearLayout.LayoutParams(
                mediaWidth,
                Math.min(
                        (int) (((double) mediaWidth / (double) bannerWidth) * bannerHeight),
                        metrics.heightPixels / 3)));
        nativeAdMedia.setNativeAd(nativeAd);

        // Wire up the View with the native ad, the whole nativeAdContainer will be clickable.
        nativeAd.registerViewForInteraction(adView);
    }
}

Leave a Reply

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