onResume 中的 NullPointerException,与 AdMob 相关,但不知道为什么
我在应用程序中的以下代码中遇到空指针异常:
@Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
// Create the adView
adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);
// Add the adView to it
layout.addView(adView); //NullPointerException here
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean isButtonLabelsEnabled = sp.getBoolean("isButtonLabelsEnabled", false);
if (!isButtonLabelsEnabled) {
stripLabels();
} else {
setContentView(R.layout.languageselection);
}
}
我无法复制此问题,我已经在模拟器、Galaxy S2 设备和 ZTE 刀片上尝试了应用程序中的所有功能,但是我找不到任何问题。
我收到很多用户报告此问题,但他们没有给出任何说明原因,只是当他们尝试打开它时它会强制关闭。
也许我没有正确使用 android 生命周期?
作为解决方法,我将 AdMob 内容包装在 try/catch 中,以便它可以通过。
有什么想法吗?
I'm getting a nullpointer exception in the following code in my application :
@Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
// Create the adView
adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);
// Add the adView to it
layout.addView(adView); //NullPointerException here
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean isButtonLabelsEnabled = sp.getBoolean("isButtonLabelsEnabled", false);
if (!isButtonLabelsEnabled) {
stripLabels();
} else {
setContentView(R.layout.languageselection);
}
}
I can't replicate this issue, I've played around with all the features in my app on both the emulator, a galaxy S2 device, and a ZTE blade but I can't find any issues.
I'm getting a lot of users report this, but they don't give any indication to why, just that it forces close when they try to open it.
Perhaps I'm not using the android life-cycle correctly?
As a workaround, I've wrapped the AdMob stuff in a try/catch so it can pass through.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在 onCreate 方法中获取 LinearLayout 对象,而不是在 onResume 方法中获取它。希望这对你有用。
Try getting your LinearLayout object in onCreate method instead of getting it in onResume method. Hope this works for you.
尝试这样:
Try like this: