1

Estoy siguiendo estas guías (empezar y anuncios bonificados) para tratar de cargar un anuncio con una id de prueba. La clase Java es la siguiente:

package com.geologyapplications.minerals;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class Shop extends AppCompatActivity {
private RewardedAd mRewardedAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shop);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#000000"));
    toolbar.setBackground(colorDrawable);
    toolbar.setTitleTextColor(Color.WHITE);
    SQLiteDatabase db = openOrCreateDatabase("coins.db", MODE_PRIVATE, null);
    Cursor cursor = db.rawQuery("SELECT COINS FROM COINS", null);
    int coins = 0;
    while (cursor.moveToNext()) {
        coins = cursor.getInt(0);
        cursor.close();
    }
    db.close();
    TextView toolbarTextView = (TextView) findViewById(R.id.toolbarTextView);
    toolbarTextView.setText(String.valueOf(coins));
    MobileAds.initialize(this, initializationStatus -> {
    });
    AdRequest adRequest = new AdRequest.Builder().build();
    RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",
            adRequest, new RewardedAdLoadCallback() {

                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    // Handle the error.
                    Log.d("ADD ", loadAdError.getMessage());
                    mRewardedAd = null;
                }

                @Override
                public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                    mRewardedAd = rewardedAd;
                    Log.d("ADD ", "mReward loaded");

                }
            });
    mRewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
        @Override
        public void onAdShowedFullScreenContent() {
            // Called when ad is shown.
            Log.d("ADD", "Ad was shown.");
        }

        @Override
        public void onAdFailedToShowFullScreenContent(AdError adError) {
            // Called when ad fails to show.
            Log.d("ADD", "Ad failed to show.");
        }

        @Override
        public void onAdDismissedFullScreenContent() {
            // Called when ad is dismissed.
            // Set the ad reference to null so you don't show the ad a second time.
            Log.d("ADD", "Ad was dismissed.");
            mRewardedAd = null;
        }
    });
    Button btnAdd = findViewById(R.id.btnAdd);
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRewardedAd != null) {
                Activity activityContext = Shop.this;
                mRewardedAd.show(activityContext, new OnUserEarnedRewardListener() {
                    @Override
                    public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                        // Handle the reward.
                        daCoinsAdd();
                        int rewardAmount = rewardItem.getAmount();
                        String rewardType = rewardItem.getType();
                    }
                });
            } else {
                Log.d("Reward ", "The rewarded ad wasn't ready yet.");
            }
        }
    });
}
public void daCoinsAdd() {
    SQLiteDatabase db = openOrCreateDatabase("coins.db", MODE_PRIVATE, null);
    Cursor cursor = db.rawQuery("SELECT COINS FROM COINS", null);
    int coins = 0;
    while (cursor.moveToNext()) {
        coins = cursor.getInt(0);
        cursor.close();
    }
    db.close();
    int newCoins = coins +300;
    String update = "UPDATE COINS SET COINS="+newCoins+"";
    db = openOrCreateDatabase("coins.db", MODE_PRIVATE, null);
    db.execSQL(update);
    db.close();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.item_back) {
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_coins, menu);
    return true;
}
}

Me da el siguiente error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geologyapplications.minerals/com.geologyapplications.minerals.Shop}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewarded.RewardedAd.setFullScreenContentCallback(com.google.android.gms.ads.FullScreenContentCallback)' on a null object reference

He seguido los pasos de la guía y no entiendo por qué me da este error. Aparentemente el método que rellena ese objeto onAdLoaded no se carga y entonces el objeto vale null.

¿Hay algo mal en mi código?

El Logcat dice lo siguiente:

2021-11-11 13:45:27.184 5395-5438/com.google.android.gms I/Icing: IndexChimeraService.getServiceInterface callingPackage=com.google.android.googlequicksearchbox componentName=null serviceId=21
2021-11-11 13:45:27.188 5395-5424/com.google.android.gms W/Icing: No valid account for uploading user actions
2021-11-11 13:45:27.193 5395-5424/com.google.android.gms I/Icing: Usage reports ok 0, Failed Usage reports 0, indexed 0, rejected 0
2021-11-11 13:45:27.202 5395-5431/com.google.android.gms I/Icing: IndexChimeraService.getServiceInterface callingPackage=com.google.android.gms componentName=null serviceId=30
2021-11-11 13:45:27.206 5395-5424/com.google.android.gms W/Icing: No valid account for uploading user actions
2021-11-11 13:45:27.207 5395-5424/com.google.android.gms I/Icing: Usage reports ok 0, Failed Usage reports 0, indexed 0, rejected 0
2021-11-11 13:46:00.011 1960-2502/com.android.systemui D/EGL_emulation: eglMakeCurrent: 0xb43bf340: ver 2 0 (tinfo 0xb43ff3b0)
2
  • ¿Lo incluiste en el manifest? ¿Lo incluiste en tu layout? el 11 nov. 2021 a las 17:48
  • @Franqo Balsamo En el manifest sí, pero en la documentación no aparece nada de xml. No es un banner es un vídeo bonificado. Creo que el problema es que mi aplicación no está publicada, y está pendiente de revisión en AdMob.
    – user219111
    el 11 nov. 2021 a las 17:51

1 respuesta 1

1

De acuerdo a el mensaje de error:

Unable to start activity ComponentInfo{com.geologyapplications.minerals/com.geologyapplications.minerals.Shop}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewarded.RewardedAd.setFullScreenContentCallback

El problema se encuentra en que debes asegurar se cargo el anuncio (onAdLoaded()) y posteriormente llamar setFullScreenContentCallback()

@Override
public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
       mRewardedAd = rewardedAd;
       Log.d("ADD ", "mReward loaded");

     /*------------------------------------------*/
    mRewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
           @Override
           public void onAdShowedFullScreenContent() {
               // Called when ad is shown.
              Log.d("ADD", "Ad was shown.");
           }

           @Override
           public void onAdFailedToShowFullScreenContent(AdError adError) {
               // Called when ad fails to show.
               Log.d("ADD", "Ad failed to show.");
           }

           @Override
           public void onAdDismissedFullScreenContent() {
               // Called when ad is dismissed.
               // Set the ad reference to null so you don't show the ad a second time.
               Log.d("ADD", "Ad was dismissed.");
               mRewardedAd = null;
           }
       });
     /*------------------------------------------*/
     

     }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.