【发布时间】:2020-01-01 09:45:38
【问题描述】:
我一直在尝试将 AdMob 横幅广告代码添加到我的应用中。当我尝试这样做时,我在 adView.loadAd(adRequest) 上收到 Null Pointer Exception 错误。
另一个错误是我的应用在 android lollipop os 上崩溃。如何解决这个问题。帮帮我。我是安卓新手。
这是我的布局 xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<include android:layout_width="match_parent" android:layout_height="wrap_content" layout="@layout/ab"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_main_f" />
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
ads:adSize="SMART_BANNER"
ads:adUnitId="@string/banner_ad" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
这是我的主要活动.java
public class MainActivity extends AppCompatActivity {
public InterstitialAd mInterstitialAd;
private ShareActionProvider mProvider;
private long mLong;
private Toast mToast;
private AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_f);
//Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Maths Text View
TextView mathsView = findViewById(R.id.maths);
//Set Maths onClickListener
mathsView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Step 2.2: Start the new activity
Intent mathsIntent = new Intent(MainActivity.this, Maths.class);
startActivity(mathsIntent);
}
});
//Physics Text View
TextView physicsView = findViewById(R.id.physics);
//Set Physics onClickListener
physicsView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Step 2.2: Start the new activity
Intent physicsIntent = new Intent(MainActivity.this, Physics.class);
startActivity(physicsIntent);
}
});
//Chemistry Text View
TextView chemistryView = findViewById(R.id.chemistry);
//Set Chemistry onClickListener
chemistryView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent chemistryIntent = new Intent(MainActivity.this, Chemistry.class);
startActivity(chemistryIntent);
}
});
//Extra Text View
TextView extraView = findViewById(R.id.extra);
//Set Extra onClickListener
extraView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent extraIntent = new Intent(MainActivity.this, Extra.class);
startActivity(extraIntent);
}
});
//Premium Version
Button pre = findViewById(R.id.btn_premium);
pre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String appPackageName = "xxxxxxxxxxxxx"; // package name of the app
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
//Ads Initialize
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Google Banner Ads added
adView = this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Google InterstitialAd Ads added
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.inst_ad));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
@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_main, menu);
//share the app
MenuItem menuItem = menu.findItem(R.id.action_share);
mProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
setShareActionIntent("https://play.google.com/store/apps/details?id=");
return super.onCreateOptionsMenu(menu);
}
private void setShareActionIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String str2 = text + getPackageName();
intent.putExtra(Intent.EXTRA_SUBJECT, "All In One Formula");
intent.putExtra(Intent.EXTRA_TEXT, str2);
mProvider.setShareIntent(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.rate_us) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + this.getPackageName())));
} catch (ActivityNotFoundException e) {
e.printStackTrace();
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
}
return true;
} else if (id == R.id.about_us) {
Intent extraIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(extraIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
@Override
protected void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/**
* Called before the activity is destroyed
*/
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
//Double press to exit!
@Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();
if (currentTime - mLong > 5000) {
mToast = Toast.makeText(getBaseContext(), getString(R.string.back_pressed), Toast.LENGTH_LONG);
mToast.show();
mLong = currentTime;
} else {
if (mToast != null) mToast.cancel();
super.onBackPressed();
}
}
}
另一个活动代码(Intent)
public class Maths extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
//Set String value in adapter
private final String[] n = new String[]{"Basic Algebra", "Indices", "Vector Addition and Subtraction", "Mathematical Properties",
"Percentage Formulas", "Simple and Compound Interest", "Mensuration", "Binary Numbers", "Probability Formulas",
"Celsius Formulas", "Angle Formulas", "Antiderivative", "Calculus Formulas", "Trigonometry Formulas", "Identities and Triangle"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maths);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//Call final list with id
//Call List View
ListView listView = findViewById(R.id.list_maths);
//Google Ads added
AdView adView = this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.inst_ad));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
/*
* Set the adapter In Maths class to showing list String
* */
listView.setAdapter(new ArrayAdapter<>(this, R.layout.list_basic_learn, R.id.item_name_basiclist, this.n));
//Enable Text clickable
listView.setClickable(true);
//Set OnItemClickListener to Maths layout
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Transfer the data to all Maths sub class
switch (position) {
case 0:
Maths.this.startActivity(new Intent(Maths.this, BasicAlgebra.class));
break;
case 1:
Maths.this.startActivity(new Intent(Maths.this, Indices.class));
break;
case 2:
Maths.this.startActivity(new Intent(Maths.this, VectorAdditionMath.class));
break;
case 3:
Maths.this.startActivity(new Intent(Maths.this, MathematicalProperties.class));
break;
case 4:
Maths.this.startActivity(new Intent(Maths.this, PercentageFormula.class));
break;
case 5:
Maths.this.startActivity(new Intent(Maths.this, SimpleandCompoundInterest.class));
break;
case 6:
Maths.this.startActivity(new Intent(Maths.this, Mensuration.class));
break;
case 7:
Maths.this.startActivity(new Intent(Maths.this, BinaryNumbers.class));
break;
case 8:
Maths.this.startActivity(new Intent(Maths.this, ProbabilityFormulas.class));
break;
case 9:
Maths.this.startActivity(new Intent(Maths.this, CelsiusFormula.class));
break;
case 10:
Maths.this.startActivity(new Intent(Maths.this, AngleFormula.class));
break;
case 11:
Maths.this.startActivity(new Intent(Maths.this, Antiderivative.class));
break;
case 12:
Maths.this.startActivity(new Intent(Maths.this, CalculusFormula.class));
break;
case 13:
Maths.this.startActivity(new Intent(Maths.this, TrigonometryFormula.class));
break;
case 14:
Maths.this.startActivity(new Intent(Maths.this, Identities.class));
break;
default:
}
}
});
}
//Destroy the class when going back
public void onBackPressed() {
super.onBackPressed();
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
finish();
}
}
有人可以帮我解决这个问题吗?谢谢。
【问题讨论】:
-
你应该首先检查是否 ad.isLoaded,如果它已加载,你可以使用 ad.show() 或你想要的东西!
-
请发布 logcat。
-
这是我的 Logcat...pastebin.com/Eaq6cct2
-
有人帮我吗?尽管如此,我还是把代码堆起来了!!
标签: java android android-studio nullpointerexception