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
204
27
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

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

A Null Pointer Exception occurs when the program tries to access an object or variable that does not exist. This can happen when the program is not properly initialized or when there is a programming error. In the case of running rewarded ads, it could be caused by a missing or incorrectly initialized ad object.

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

To fix a Null Pointer Exception when running rewarded ads, you should carefully review your code to ensure that all necessary variables and objects are properly initialized and that there are no programming errors. You may also need to check the documentation for the ad platform you are using to ensure that you are following all necessary steps for implementing rewarded ads.

3. Can network connectivity issues cause a Null Pointer Exception when running rewarded ads?

Yes, network connectivity issues can sometimes cause a Null Pointer Exception when running rewarded ads. If the ad platform requires an internet connection and the device is not connected to the internet, the program may try to access an object or variable related to the ad and result in a Null Pointer Exception. It is important to handle network connectivity issues in your code to prevent this from occurring.

4. Are there any common mistakes that can lead to a Null Pointer Exception when running rewarded ads?

Yes, some common mistakes that can lead to a Null Pointer Exception when running rewarded ads include not properly initializing ad objects, not following the correct implementation steps for the ad platform, and not handling network connectivity issues. It is important to carefully review your code and follow all necessary steps to avoid these mistakes.

5. Is there a way to prevent a Null Pointer Exception when running rewarded ads?

While it is not always possible to completely prevent a Null Pointer Exception, there are steps you can take to reduce the likelihood of it occurring. These include carefully reviewing and testing your code, following the correct implementation steps for the ad platform, and handling potential network connectivity issues. It is also important to regularly monitor and update your code to address any potential issues that may arise.

Similar threads

  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
6
Views
5K
Back
Top