AdvanceNativeAd caching

22 views
Skip to first unread message

Banele Goodenough

unread,
May 20, 2024, 12:28:28 AMMay 20
to Google Mobile Ads SDK Developers
I have a project where I need to display native ads and I've loaded them using the SDK then I cache them in local room storage with a custom model ie. now when the problem is populating and have to call the setNativeAd(). Can anyone assist?

data class NativeAdEntity(
@PrimaryKey
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_AD_UNIT_ID)
val adUnitId: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_HEADLINES)
val headlines: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_BODY)
val body: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_IMAGE_URL)
val imageUrl: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_MAIN_IMAGE_URL)
val mainImageUrl: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_CALL_TO_ACTION)
val callToAction: String,
@ColumnInfo(name = NativeAdsConfigRoomDatabase.TABLE_COLUMN_TIMESTAMP)
val timestamp: Long,

)

Mobile Ads SDK Forum Advisor

unread,
May 20, 2024, 1:09:14 AMMay 20
to banel...@gmail.com, google-adm...@googlegroups.com
Hi,

Thank you for contacting us.
Kindly follow below approach once and get back to us in case you need any other help related to catching of AdvanceNative ads.
@Entity
public class CachedAd {

    @PrimaryKey(autoGenerate = true)
    public long id;

    public String adUnitId;
    public String adBody;
    public String imageUrl;

    @ColumnInfo(name = "cached_at")
    public long cachedAt; // Timestamp when the ad was cached

    // Optional fields for targeting, etc.
    // ...
}


Then Implement Room Persistence (Using an AdDao class):

@Dao
public interface AdDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAd(CachedAd ad);

    @Query("SELECT * FROM CachedAd")
    List<CachedAd> getAllAds();

    @Query("DELETE FROM CachedAd WHERE cached_at < :threshold")
    void deleteOldAds(long threshold);
}


Ad Caching Logic (using AdManager class):

public class AdManager {

    private final AdDao adDao;

    public AdManager(AdDao adDao) {
        this.adDao = adDao;
    }

    public CompletableFuture<CachedAd> fetchNewAd(String adUnitId) {
        // Fetch ad using your SDK (replace with your actual implementation)
        CompletableFuture<String> adContentFuture = // ... (SDK call)

        return adContentFuture.thenApply(adContent -> {
            CachedAd ad = new CachedAd();
            ad.adUnitId = adUnitId;
            ad.adBody = adContent;
            // ... populate other fields
            ad.cachedAt = System.currentTimeMillis();
            cacheAd(ad);
            return ad;
        });
    }

    private void cacheAd(CachedAd ad) {
        adDao.insertAd(ad);
    }

    public CachedAd getCachedAd(String adUnitId) {
        List<CachedAd> cachedAds = adDao.getAllAds();
        for (CachedAd ad : cachedAds) {
            if (ad.adUnitId.equals(adUnitId)) {
                // Check for freshness (optional)
                long freshnessThreshold = 3600000; // 1 hour in milliseconds
                if (System.currentTimeMillis() - ad.cachedAt < freshnessThreshold) {
                    return ad;
                } else {
                    // Refetch ad if it's old
                    fetchNewAd(adUnitId);
                    return null; // Indicate ad is being refetched
                }
            }
        }
        return null; // No cached ad found
    }

    public void setNativeAd(View adView, String adUnitId) {
        CachedAd ad = getCachedAd(adUnitId);
        if (ad != null) {
            // Populate the native ad view with the cached ad data
            // (Replace with your ad view's specific population logic)
            // ...
        } else {
            // Show a loading indicator

I hope this will help you.
 
This message is in relation to case "ref:!00D1U01174p.!5004Q02tJ1jQ:ref" (ADR-00235661)

Thanks,
 
Google Logo Mobile Ads SDK Team


Banele Goodenough

unread,
May 20, 2024, 6:37:10 AMMay 20
to Mobile Ads SDK Forum Advisor, google-adm...@googlegroups.com
Thank you for your response and I have already implemented what you  have suggested issue is when I have to call setNativesAd() which accept the NativeAd object which cannot be reassigned. 

My question is how to map the cached to NativeAd object?

Mobile Ads SDK Forum Advisor

unread,
May 20, 2024, 6:54:19 AMMay 20
to banel...@gmail.com, google-adm...@googlegroups.com

Hi,
 

NativeAd responses can be maintain in cache too. For this you have to make sure how many ad you want to put on cache. On that basis create object in cache directory which will accept array of NativeAd.

Then on background just save native ad response into cache depending upon your logics from where you wanted to prefetch.

private fun refreshAd() {

  val builder = AdLoader.Builder(this, ADMOB_AD_UNIT_ID)

  builder.forNativeAd { nativeAd ->

// Here you will receive  NativeAd, it can save into cache and break the control here for next ad.

The moment when you wanted to show the ad.  Take reference from cache and get the nativeAd Object too which saved above.

currentNativeAd = nativeAd // Take through cache

val unifiedAdBinding = AdUnifiedBinding.inflate(layoutInflater)

populateNativeAdView(nativeAd, unifiedAdBinding)

mainActivityBinding.adFrame.removeAllViews()

mainActivityBinding.adFrame.addView(unifiedAdBinding.root)

nativeAdView.setNativeAd(nativeAd)

And Here nativeAd is an ad object which will pass through populateNativeAdView argument.

Reply all
Reply to author
Forward
0 new messages