简体   繁体   中英

Application crash for no reason after using rewarded ad from Admob

My application always crashes when I click the button to play video rewarded ad, but after I checked out all files, it showed no error. And, I have tested it on a virtual machine (API level 30) and my phone (API level 28), this situation happened all the time.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.xxx">
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="xxx"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.xxx">

    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-xxx"/>

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

build.gradle file:

buildscript {
repositories {
    google()
    mavenCentral()
   
}
dependencies {
    classpath 'com.android.tools.build:gradle:7.0.4'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
 }
allprojects {
  repositories {
  google()
  mavenCentral()
 }
}

task clean(type: Delete) {
  delete rootProject.buildDir
}

build.gradle(:app) file:

plugins {
id 'com.android.application'
}

android {
compileSdk 31

defaultConfig {
    applicationId "com.example.xxx"
    minSdk 21
    targetSdk 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
 }


}



dependencies {


//noinspection GradleCompatible
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'


//noinspection GradleCompatible
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

implementation 'com.google.android.gms:play-services-ads:20.5.0'

implementation "androidx.constraintlayout:constraintlayout:2.1.3"

}

java file:

 import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.ImageButton;
 import android.widget.TextView;

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

 import com.google.android.gms.ads.AdError;
 import com.google.android.gms.ads.AdRequest;
 import com.google.android.gms.ads.AdView;
 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.rewarded.RewardedAd;
 import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;

public class MainActivity extends Activity implements View.OnClickListener {
private RewardedAd mRewardedAd;
private static final String TAG = "MainActivity";
private final TextView textView2 = findViewById(R.id.textView2);

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

    ImageButton btn = findViewById(R.id.imageButton);
    btn.setOnClickListener(this);

    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
            loadRewardedAd();
        }
    });


}

private void loadRewardedAd() {
    AdView adView = findViewById(R.id.adView2);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    AdRequest adRequest2 = new AdRequest.Builder().build();

    RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",
            adRequest2, new RewardedAdLoadCallback() {
                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    // Handle the error.
                    Log.d(TAG, loadAdError.getMessage());
                    mRewardedAd = null;
                    Log.d(TAG, "Ad was failed to load");
                }

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

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

                        }

                        @Override
                        public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                            // Called when ad fails to show.
                            Log.d(TAG, "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(TAG, "Ad was dismissed.");

                        }
                    });
                }
            });
}

private void showRewardedAd() {
    if (mRewardedAd != null) {
        mRewardedAd.show(this, new OnUserEarnedRewardListener() {
            @Override
            public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                // Handle the reward.
                Log.d(TAG, "The user earned the reward.");
                int rewardAmount = rewardItem.getAmount();
                String rewardType = rewardItem.getType();

                int reward = Integer.parseInt(textView2.getText().toString().trim());
                textView2.setText(String.valueOf(reward+1));
            }
        });
    } else {
        Log.d(TAG, "The rewarded ad wasn't ready yet.");
    }
 }

@Override
public void onClick(View view) {
    showRewardedAd();
 }

}

Logcat:

2022-01-23 09:17:19.713 2679-2723/com.example.earningsdk E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@8b42ae7 2022-01-23 09:17:19.715 2679-2723/com.example.earningsdk E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@f72d694 2022-01-23 09:17:19.848 2679-2711/com.example.earningsdk E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist: 2022-01-23 09:17.19.880 2679-2679/com.example:earningsdk E/AndroidRuntime: FATAL EXCEPTION: main Process. com.example,earningsdk: PID. 2679 java.lang:RuntimeException. Unable to instantiate activity ComponentInfo{com.example.earningsdk/com.example.earningsdk:MainActivity}. java.lang:NullPointerException. Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread:java.3355) at android.app.ActivityThread.handleLaunchActivity(ActivityThread:java.3614) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem:java.86) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor:java.108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor:java.68) at android.app.ActivityT hread$H.handleMessage(ActivityThread:java.2199) at android.os.Handler.dispatchMessage(Handler:java.112) at android.os.Looper.loop(Looper:java.216) at android.app.ActivityThread.main(ActivityThread:java.7625) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit:java.524) at com.android.internal.os.ZygoteInit.main(ZygoteInit:java:987) Caused by. java.lang:NullPointerException. Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.Activity.findViewById(Activity:java.2823) at com.example.earningsdk.MainActivity.(MainActivity:java.30) at java.lang.Class.newInstance(Native Method) at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory:java.69) at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory:java.45) at android.app.Instrumentation.newActivity(Instrumentation:java.1224) at android .app.ActivityThread.performLaunchActivity(ActivityThread:java.3340) at android.app.ActivityThread.handleLaunchActivity(ActivityThread:java.3614) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem:java.86) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor:java.108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor:java.68) at android.app.ActivityThread$H.handleMessage(ActivityThread:java.2199) at android.os.Handler.dispatchMessage(Handler:java.112) at android.os.Looper.loop(Looper:Z93F725A074 23FE1C889F448B33D21F46Z.216) at android.app.ActivityThread.main(ActivityThread:java.7625) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit:java.524) at com.android.internal.os.ZygoteInit.main(ZygoteInit:java:987)

I think I found the reason, the logcat said "Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at MainActivity.java:30", it worked well after I deleted it. But, I still don't know what's the cause of this error and how do I fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM