Why do I get a Null Pointer Exception when I try to run rewarded ads?

  • Thread starter Darkmisc
  • Start date
In summary: Called when the fullscreen callback is done. public void onAdDismissed() { // Called when the ad is dismissed. // Set the ad reference to null so you don't show the ad
  • #1
Darkmisc
221
31
TL;DR Summary
I copied code from the Admob developer page for a rewarded ad and it doesn't work. I get a Null Pointer Exception.
Hi everyone

I've cut and pasted code from here to test rewarded interstitial ads. https://developers.google.com/admob/android/rewarded-interstitial
The only change I've made is to call the ad upon a button click.

When I click the button to call the ad, the program crashes and makes reference to a Null Pointer Exception caused by the following lines:
line with error:
rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
    OnUserEarnedRewardListener */ MainActivity.this);

Does anyone know why this is happening?

Full code and stacktrace below.
Thanks
MainActivity:
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
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.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd;
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback;

public class MainActivity extends AppCompatActivity implements OnUserEarnedRewardListener {
    private RewardedInterstitialAd rewardedInterstitialAd;
    private String TAG = "MainActivity";

    TextView textView;
    Button button;
    int value;

    @Override
    public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
        Log.i(TAG, "User earned reward.");
        value++;
        textView.setText(String.valueOf(value));
    }

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

        int value =0;
        textView = findViewById(R.id.textView);
        textView.setText(String.valueOf(value));
        button = findViewById(R.id.button);        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

loadAd();
    }

    public void onClick (View view){
        **rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
    OnUserEarnedRewardListener */ MainActivity.this);**
    }

    public void loadAd(){
        RewardedInterstitialAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
                new AdRequest.Builder().build(), new RewardedInterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(RewardedInterstitialAd ad) {
                        rewardedInterstitialAd = ad;
                        rewardedInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                            @Override
                            public void onAdClicked() {
                                // Called when a click is recorded for an ad.
                                Log.d(TAG, "Ad was clicked.");
                            }

                            @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(TAG, "Ad dismissed fullscreen content.");
                                rewardedInterstitialAd = null;
                            }

                            @Override
                            public void onAdFailedToShowFullScreenContent(AdError adError) {
                                // Called when ad fails to show.
                                Log.e(TAG, "Ad failed to show fullscreen content.");
                                rewardedInterstitialAd = null;
                            }

                            @Override
                            public void onAdImpression() {
                                // Called when an impression is recorded for an ad.
                                Log.d(TAG, "Ad recorded an impression.");
                            }

                            @Override
                            public void onAdShowedFullScreenContent() {
                                // Called when ad is shown.
                                Log.d(TAG, "Ad showed fullscreen content.");
                            }
                        });
                    }
                    @Override
                    public void onAdFailedToLoad(LoadAdError loadAdError) {
                        Log.d(TAG, loadAdError.toString());
                        rewardedInterstitialAd = null;
                    }
                });
    }
  }

Here is the stacktrace.
stacktrace:
E  FATAL EXCEPTION: main
                                                                                                    Process: com.xxmassdeveloper.rewardedads2, PID: 20217
                                                                                                    java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
                                                                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
                                                                                                    **Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd.show(android.app.Activity, com.google.android.gms.ads.OnUserEarnedRewardListener)' on a null object reference
                                                                                                        at com.xxmassdeveloper.rewardedads2.MainActivity.onClick(MainActivity.java:64)**
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
2023-02-01 10:30:03.908 20217-20217 Process                 com.xxmassdeveloper.rewardedads2     I  Sending signal. PID: 20217 SIG: 9
---------------------------- PROCESS ENDED (20217) for package com.xxmassdeveloper.rewardedads2 ----------------------------
2023-02-01 10:30:04.207  3675-5653  WindowManager           pid-3675                             E  win=Window{81ddba7 u0 com.xxmassdeveloper.rewardedads2/com.xxmassdeveloper.rewardedads2.MainActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
 
Last edited:
Technology news on Phys.org
  • #2
Darkmisc said:
When I click the button to call the ad, the program crashes and makes reference to a Null Pointer Exception caused by the following lines:
line with error:
rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
    OnUserEarnedRewardListener */ MainActivity.this);

Does anyone know why this is happening?
You were supposed to pass an instance of the Activity class and OnUserEarnedRewardListener interface. Why are you passing MainActivity.this? Just pass this, you are already inside the MainActivity class, which is also an instance of the interface as you have implemented it.

The correct method call would be:
Corrected code:
rewardedInterstitialAd.show(this, this);

Classname.this is a different thing. See https://stackoverflow.com/q/45637427/8387076

Also, your deleted question on Stack Overflow is still popping up in search queries o0)
 
Last edited:
  • Like
  • Haha
Likes Darkmisc and jedishrfu
  • #3
Thanks. It worked, but I can only click on the button once and see an ad. If I try to watch more than one ad in a row, the program crashes (stacktrace below).

If I wait a bit and then try, I can see the ad again, but I can't click the button again without a crash.

Does this have anything to do with load times? I don't understand why the button shouldn't work all the time.

stacktrace:
FATAL EXCEPTION: main
                                                                                                    Process: com.xxmassdeveloper.rewardedads2, PID: 6960
                                                                                                    java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
                                                                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd.show(android.app.Activity, com.google.android.gms.ads.OnUserEarnedRewardListener)' on a null object reference
                                                                                                        at com.xxmassdeveloper.rewardedads2.MainActivity.onClick(MainActivity.java:65)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
                                                                                                        at android.view.View.performClick(View.java:7870)
                                                                                                        at android.widget.TextView.performClick(TextView.java:14970)
                                                                                                        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
                                                                                                        at android.view.View.performClickInternal(View.java:7839)
                                                                                                        at android.view.View.access$3600(View.java:886)
                                                                                                        at android.view.View$PerformClick.run(View.java:29363)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:883)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                                        at android.os.Looper.loop(Looper.java:237)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7948)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
2023-02-02 11:45:28.182  6960-6960  Process                 com.xxmassdeveloper.rewardedads2     I  Sending signal. PID: 6960 SIG: 9
---------------------------- PROCESS ENDED (6960) for package com.xxmassdeveloper.rewardedads2 ----------------------------
2023-02-02 11:45:28.304  3675-5805  WindowManager           pid-3675                             E  win=Window{e12d993 u0 com.xxmassdeveloper.rewardedads2/com.xxmassdeveloper.rewardedads2.
    
    Activity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
 
  • #4
One error I see is that in the full code you posted in the OP, the loadAd() method call at line 58 should be inside the nested class, i.e. between lines 54 and 55.

Note that in the loadAd() method, you are inside a nested class, you have to use MainActivity.this instead of just this, which is what you've already done.

If this change doesn't solve the issue, then I think you have to initialize the ad again once it has been showed (call the nested class callback from line 52 again). Separate this portion out in a method to call easily.
 
  • Like
Likes Darkmisc

FAQ: Why do I get a Null Pointer Exception when I try to run rewarded ads?

Why do I get a Null Pointer Exception when I try to run rewarded ads?

A Null Pointer Exception occurs when you are trying to access a reference variable that is pointing to null. This means that the variable is not pointing to any object in memory, causing the program to crash when trying to access it.

How can I fix a Null Pointer Exception when running rewarded ads?

To fix a Null Pointer Exception when running rewarded ads, you will need to carefully check your code for any variables that may be null before accessing them. Make sure to properly initialize all necessary objects before using them in your code.

Are there common causes for Null Pointer Exceptions when working with rewarded ads?

Common causes for Null Pointer Exceptions when working with rewarded ads include not properly initializing ad objects, not checking for null values before accessing variables, and passing null values as arguments to methods that do not handle them correctly.

How can I prevent Null Pointer Exceptions from occurring when running rewarded ads?

To prevent Null Pointer Exceptions when running rewarded ads, it is important to always check for null values before accessing variables or objects. Additionally, make sure to handle null values appropriately in your code to avoid crashes.

Is there a way to debug a Null Pointer Exception related to rewarded ads?

Yes, you can debug a Null Pointer Exception related to rewarded ads by using tools like a debugger to step through your code and identify the exact location where the null value is causing the issue. Additionally, logging statements can help you track the flow of your code and pinpoint the source of the exception.

Similar threads

Replies
6
Views
6K
Back
Top