invertase / react-native-google-mobile-ads

React Native Google Mobile Ads enables you to monetize your app with AdMob.
https://docs.page/invertase/react-native-google-mobile-ads
Other
673 stars 135 forks source link

[🐛] Rewarded Ads not loading on Android - RewardedAd.show() The requested RewardedAd has not loaded and could not be shown #461

Closed usmanr626 closed 6 months ago

usmanr626 commented 1 year ago

What happened?

I am getting this error RewardedAd.show() The requested RewardedAd has not loaded and could not be shown, I have called rewarded.show() on a button press, its working fine on iOS but getting this error on android, also it was working fine like a week ago.

the library I am using : "react-native-google-mobile-ads": "^12.1.2",

useEffect(() => { const unsubscribeLoaded = rewarded.addAdEventListener( RewardedAdEventType.LOADED, () => { setLoaded(true); console.log('Rewarded Ad Loaded'); }, ); const unsubscribeEarned = rewarded.addAdEventListener( RewardedAdEventType.EARNED_REWARD,

   () => {
     console.log('User earned reward of ', reward);

  },
);

rewarded.load();

return () => {
  unsubscribeLoaded();
  unsubscribeEarned();
};

}, []);

I have called a function on a button press

const showAd = async () => {

setReloadAd(false); setTimeout(() => { rewarded.show(); }, 3000); };

wether I use the setTimeout or not, I can't get it to work on Android.

although Interstitial ads are working perfectly

Platforms

Only on Android

React Native Info

(node:61525) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
System:
  OS: macOS 13.5.2
  CPU: (8) arm64 Apple M2
  Memory: 64.14 MB / 8.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 19.8.1
    path: /opt/homebrew/bin/node
  Yarn:
    version: 1.22.19
    path: /opt/homebrew/bin/yarn
  npm:
    version: 9.5.1
    path: /opt/homebrew/bin/npm
  Watchman:
    version: 2023.03.13.00
    path: /opt/homebrew/bin/watchman
Managers:
  CocoaPods:
    version: 1.12.1
    path: /Users/usmanrashid/.rvm/gems/ruby-2.7.6/bin/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 22.4
      - iOS 16.4
      - macOS 13.3
      - tvOS 16.4
      - watchOS 9.4
  Android SDK: Not Found
IDEs:
  Android Studio: 2022.1 AI-221.6008.13.2211.9619390
  Xcode:
    version: 14.3/14E222b
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 11.0.18
    path: /usr/bin/javac
  Ruby:
    version: 2.7.6
    path: /Users/usmanrashid/.rvm/rubies/ruby-2.7.6/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.72.3
    wanted: 0.72.3
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: false

Are your using Typescript?

package.json

{
  "name": "aichatbot",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "eslint .",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.19.1",
    "@react-native-firebase/app": "^18.3.0",
    "@react-native-firebase/remote-config": "^18.3.0",
    "@react-native-firebase/analytics": "^18.3.0",
    "@react-native-voice/voice": "^3.2.4",
    "@react-navigation/drawer": "^6.6.3",
    "@react-navigation/native": "^6.1.7",
    "@react-navigation/native-stack": "^6.9.13",
    "axios": "^1.4.0",
    "react": "18.2.0",
    "react-native": "0.72.3",
    "react-native-axios": "^0.17.1",
    "react-native-gesture-handler": "^2.12.0",
    "react-native-google-mobile-ads": "^12.1.2",
    "react-native-modal": "^13.0.1",
    "react-native-permissions": "^3.8.4",
    "react-native-radial-gradient": "^1.1.3",
    "react-native-reanimated": "^3.3.0",
    "react-native-safe-area-context": "^4.7.1",
    "react-native-screens": "^3.22.1",
    "react-native-tracking-transparency": "^0.1.2"
  },
  "reactNativePermissionsIOS": [
    "AppTrackingTransparency",
    "BluetoothPeripheral",
    "Calendars",
    "Camera",
    "Contacts",
    "FaceID",
    "LocationAccuracy",
    "LocationAlways",
    "LocationWhenInUse",
    "MediaLibrary",
    "Microphone",
    "Motion",
    "Notifications",
    "PhotoLibrary",
    "PhotoLibraryAddOnly",
    "Reminders",
    "Siri",
    "SpeechRecognition",
    "StoreKit"
  ],
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/preset-env": "^7.20.0",
    "@babel/runtime": "^7.20.0",
    "@react-native/eslint-config": "^0.72.2",
    "@react-native/metro-config": "^0.72.7",
    "@tsconfig/react-native": "^3.0.0",
    "@types/metro-config": "^0.76.3",
    "@types/react": "^18.0.24",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.2.1",
    "eslint": "^8.19.0",
    "jest": "^29.2.1",
    "metro-react-native-babel-preset": "0.76.5",
    "prettier": "^2.4.1",
    "react-test-renderer": "18.2.0",
    "typescript": "4.8.4"
  },
  "engines": {
    "node": ">=16"
  }
}

app.json

{
  "name": "AI Chatbot",
  "displayName": "AI Chatbot",

  "react-native-google-mobile-ads": {
    "android_app_id": "ca-app-pub-4161728863134324~XXXXX",
    "ios_app_id": "ca-app-pub-4161728863134324~XXXXX",
    "user_tracking_usage_description": "This identifier will be used to deliver personalized ads to you.",
    "sk_ad_network_items": [
      "cstr6suwn9.skadnetwork",
      "4fzdc2evr5.skadnetwork",
      "4pfyvq9l8r.skadnetwork",
      "2fnua5tdw4.skadnetwork",
      "ydx93a7ass.skadnetwork",
      "5a6flpkh64.skadnetwork",
      "p78axxw29g.skadnetwork",
      "v72qych5uu.skadnetwork",
      "ludvb6z3bs.skadnetwork",
      "cp8zw746q7.skadnetwork",
      "c6k4g5qg8m.skadnetwork",
      "s39g8k73mm.skadnetwork",
      "3qy4746246.skadnetwork",
      "3sh42y64q3.skadnetwork",
      "f38h382jlk.skadnetwork",
      "hs6bdukanm.skadnetwork",
      "prcb7njmu6.skadnetwork",
      "v4nxqhlyqp.skadnetwork",
      "wzmmz9fp6w.skadnetwork",
      "yclnxrl5pm.skadnetwork",
      "t38b2kh725.skadnetwork",
      "7ug5zh24hu.skadnetwork",
      "9rd848q2bz.skadnetwork",
      "y5ghdn5j9k.skadnetwork",
      "n6fk4nfna4.skadnetwork",
      "v9wttpbfk9.skadnetwork",
      "n38lu8286q.skadnetwork",
      "47vhws6wlr.skadnetwork",
      "kbd757ywx3.skadnetwork",
      "9t245vhmpl.skadnetwork",
      "a2p9lx4jpn.skadnetwork",
      "22mmun2rn5.skadnetwork",
      "4468km3ulz.skadnetwork",
      "2u9pt9hc89.skadnetwork",
      "8s468mfl3y.skadnetwork",
      "av6w8kgt66.skadnetwork",
      "klf5c3l5u5.skadnetwork",
      "ppxm28t8ap.skadnetwork",
      "424m5254lk.skadnetwork",
      "ecpz2srf59.skadnetwork",
      "uw77j35x4d.skadnetwork",
      "mlmmfzh3r3.skadnetwork",
      "578prtvx9j.skadnetwork",
      "4dzt52r2t5.skadnetwork",
      "gta9lk7p23.skadnetwork",
      "e5fvkxwrpn.skadnetwork",
      "8c4e2ghe7u.skadnetwork",
      "zq492l623r.skadnetwork",
      "3rd42ekr43.skadnetwork",
      "3qcr597p9d.skadnetwork"
    ]

  }
}

ios/Podfile

No response

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "33.0.0"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33

        // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
        ndkVersion = "23.1.7779620"
    }
    repositories {
        google()
        mavenCentral()
        maven {
             url "https://maven.google.com"
         }

    }
    dependencies {
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath ("com.android.support:support-core-utils:27.1.0")
        classpath 'com.google.gms:google-services:4.3.15'

    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

android/app/build.gradle

apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services' // <- Add this line

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
    // codegenDir = file("../node_modules/@react-native/codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    namespace "com.aichatbot"
    defaultConfig {
        multiDexEnabled true
        applicationId "com.aichatbot"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 6
        versionName "1.5"

    }
    signingConfigs {
        release{
             if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }

        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
        debug {
            signingConfig signingConfigs.debug
        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")
    // implementation project(':@react-native-voice_voice')
    implementation 'com.android.support:multidex:2.0.1' //enter the latest multidex version
    implementation 'com.google.android.gms:play-services-ads:22.4.0'

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

android/settings.gradle

// rootProject.name = 'AI Chatbot'
// apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
// include ':app'
// includeBuild('../node_modules/@react-native/gradle-plugin')

rootProject.name = 'AI Chatbot'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
include ':app'
includeBuild('../node_modules/@react-native/gradle-plugin')

// Include @react-native-voice_voice module
// include ':@react-native-voice_voice'
// project(':@react-native-voice_voice').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-voice/voice/android')

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

    <queries>
        <intent>
            <action android:name="android.speech.RecognitionService" />
        </intent>
    </queries>

    <application
      android:name=".MainApplication"
      android:foregroundServiceType="microphone"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

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

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>

</manifest>
usmanr626 commented 1 year ago

I encountered a similar issue and solved it. I hope the code will help you. :)

<Button
  title="showAds"
  onPress={async () => {
      let loaded = false;

      const adUnitId = __DEV__ ? TestIds.REWARDED : "ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy";

      const admob = RewardedAd.createForAdRequest(adUnitId, {
          requestNonPersonalizedAdsOnly: true,
      });

      const unsubscribeLoaded = admob.addAdEventListener(RewardedAdEventType.LOADED, () => {
          loaded = true;
          console.log("ads loaded");
          unsubscribeLoaded();
      });

      const unsubscribeEarned = admob.addAdEventListener(RewardedAdEventType.EARNED_REWARD, (reward) => {
          console.log("User earned reward of ", reward);
          unsubscribeEarned();
      });

      const showAds = async () => {
          admob.load();
          while (!loaded) await sleep(1000);
          admob.show();
      };

      await showAds();
  }}
/>

Still getting the same error, the issue is that admob.load() (or rewarded.load() in my case) doesn't work and so the listener doesn't register anything. And since the ad isn't loaded , it shows the error when I try to call admob.show() (rewarded.show() in my case)

const unsubscribeLoaded = admob.addAdEventListener( RewardedAdEventType.LOADED, () => { loaded = true; console.log('ads loaded'); //can't get to this part because the ad doesn't load unsubscribeLoaded(); }, );

        all of this is happening only on rewarded and rewardedInterstitial ads for android app open ads and interstitial ads are working fine,  and all ads work fine on ios
rss14 commented 11 months ago

Eu resolvi dessa forma...

Envolva seu código de exibição em um block try

function showAdsOnPress() { try { rewarded.show(); } catch (error) { console.log(Falhou ao abrir, error); rewarded.load(); } }

github-actions[bot] commented 10 months ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

akaoppa commented 10 months ago

Nothing work anymore since this google consent update... Always getting Error: [googleMobileAds/no-fill] No fill. even with TestAds (for rewardedAd) and ERROR Advert failed to load community: [Error: [googleMobileAds/error-code-no-fill] The ad request was successful, but no ad was returned due to lack of ad inventory.] for banners ads

github-actions[bot] commented 8 months ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

CaptainHaider commented 8 months ago

@akaoppa were you able to find any solution?

github-actions[bot] commented 7 months ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

talhaonder commented 2 months ago

I encountered a similar issue and solved it. I hope the code will help you. :)

<Button
  title="showAds"
  onPress={async () => {
      let loaded = false;

      const adUnitId = __DEV__ ? TestIds.REWARDED : "ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy";

      const admob = RewardedAd.createForAdRequest(adUnitId, {
          requestNonPersonalizedAdsOnly: true,
      });

      const unsubscribeLoaded = admob.addAdEventListener(RewardedAdEventType.LOADED, () => {
          loaded = true;
          console.log("ads loaded");
          unsubscribeLoaded();
      });

      const unsubscribeEarned = admob.addAdEventListener(RewardedAdEventType.EARNED_REWARD, (reward) => {
          console.log("User earned reward of ", reward);
          unsubscribeEarned();
      });

      const showAds = async () => {
          admob.load();
          while (!loaded) await sleep(1000);
          admob.show();
      };

      await showAds();
  }}
/>

Still getting the same error, the issue is that admob.load() (or rewarded.load() in my case) doesn't work and so the listener doesn't register anything. And since the ad isn't loaded , it shows the error when I try to call admob.show() (rewarded.show() in my case)

const unsubscribeLoaded = admob.addAdEventListener( RewardedAdEventType.LOADED, () => { loaded = true; console.log('ads loaded'); //can't get to this part because the ad doesn't load unsubscribeLoaded(); }, );

        all of this is happening only on rewarded and rewardedInterstitial ads for android app open ads and interstitial ads are working fine,  and all ads work fine on ios

Thanks its helped me alot ^^