0
我在這裏問這個問題之前已經做了大量的搜索。Recyclerview實現中Admob NativeExpressAdView的問題
我在我的Recyclerview中集成了NativeExpressAdView,如此處google example中所述,它也工作正常。但問題是,在這個示例項目中,他們從第零個位置添加NativeExpressAdView,但不想在第零個位置添加NativeExpressAdView。
我也可以隨機添加位置,但是當我們必須從代碼設置NativeExpressAdView的廣告大小時,就會出現問題。
Cardview,在MainActivity的setUpAndLoadNativeExpressAds
方法中訪問,將爲空,並且如果不在第零位添加視圖,則將給予NPE。
這是我修改後的代碼片斷
/**
* Adds Native Express ads to the items list.
*/
private void addNativeExpressAds() {
// Loop through the items array and place a new Native Express ad in every ith position in
// the items List.
for (int i = 7; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = new NativeExpressAdView(MainActivity.this);
mRecyclerViewItems.add(i, adView);
}
}
/**
* Sets up and loads the Native Express ads.
*/
private void setUpAndLoadNativeExpressAds() {
// Use a Runnable to ensure that the RecyclerView has been laid out before setting the
// ad size for the Native Express ad. This allows us to set the Native Express ad's
// width to match the full width of the RecyclerView.
mRecyclerView.post(new Runnable() {
@Override
public void run() {
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
// Set the ad size and ad unit ID for each Native Express ad in the items list.
for (int i = 7; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView =
(NativeExpressAdView) mRecyclerViewItems.get(i);
final CardView cardView = (CardView) findViewById(R.id.ad_card_view);
final int adWidth = cardView.getWidth() - cardView.getPaddingLeft()
- cardView.getPaddingRight(); //Here cardView will be Null (so NPE).
AdSize adSize = new AdSize((int) (adWidth/scale), NATIVE_EXPRESS_AD_HEIGHT);
adView.setAdSize(adSize);
adView.setAdUnitId(AD_UNIT_ID);
}
// Load the first Native Express ad in the items list.
loadNativeExpressAd(7); //Not added code for this method as nothing is modified in that.
}
});
}
即使我從回購拉動示例項目代碼後執行同樣的變化這個問題來了。
這裏是我的logcat崩潰
FATAL EXCEPTION: main
java.lang.NullPointerException at com.google.android.gms.example.nativeexpressrecyclerviewexample.MainActivity$1.run(MainActivity.java:106)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
因此,這是某種錯誤的或我在做什麼錯。
你的意思是說我一直初始化for循環從i = 0只,並添加如果條件,如果我!= 0添加NativeExpressAdView否則不? –
是的,你必須從0開始,但由條件,這避免索引0 –
試試這可能會有所幫助它適用於我 –