Unable to initialize native ad inside recyclerview in androidX

爷,独闯天下 提交于 2020-08-10 19:21:32

问题


I was trying to implement Admob native ads inside my recyclerView, And i ended with below error & i have also attached my code. i even followed Google Code Lab. Still i ended with multiple error.

How do i add native ad's between <Arraylist>.

FYI: i have minimized code to be readable.

MainActivity:

public class MainActivity extends AppCompatActivity {

public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;

@BindView(R.id.recyclerView) RecyclerView recyclerView;

ArrayList<VideoModel> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());

    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    adMob();
    arrayListVideos = new ArrayList<>();

    mLayoutManager = new GridLayoutManager(this, autoCardWith);
    //mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
       // @Override
        //public int getSpanSize(int position) {  if (position % MainActivity.ITEMS_PER_AD == 0) {  return autoCardWith; } return 1;      }
    //});
    recyclerView.setHasFixedSize(true);
    //recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
    recyclerView.setHasFixedSize(true);
    shimmerFrameLayout = findViewById(R.id.shimmer_view);
    shimmerFrameLayout.setVisibility(View.VISIBLE);
    shimmerFrameLayout.startShimmer();
    recyclerView.setVisibility(View.INVISIBLE);

    askPermission();
    
    displayAllVideos();
    
    loadNativeAds();
        
}

private void loadNativeAds() {
    AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));

    adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
        @Override
        public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
            nativeAds.add(unifiedNativeAd);
            if (!adLoader.isLoading()) {
                insertAdsinMenuItem();
            }
        }
    }).withAdListener(new AdListener() {
        @Override
        public void onAdFailedToLoad(int i) {
            super.onAdFailedToLoad(i);
            if (!adLoader.isLoading()) {
                insertAdsinMenuItem();
            }
        }
    }).build();

    adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}

private void insertAdsinMenuItem() {
    if (nativeAds.size() < 0 ){
        return;
    }
    int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
    int index = 0;

    for (UnifiedNativeAd ad:nativeAds){
        arrayListVideos.add(index,ad);
        index = index + offset;
    }

}

private void adMob() {
    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
        }
    });
    mAdView = findViewById(R.id.main_banner);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}

private void askPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:"+getPackageName()));
        startActivityForResult(intent,2084);
    }
}

private void displayAllVideos() {
    Uri uri;
    Cursor cursor;
    int column_index_data,thum;

    String absolutePathThumb;
    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};

    final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
    cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

    while (cursor.moveToNext()){
        Log.d("VIDEO", cursor.getString(0));
        absolutePathThumb = cursor.getString(column_index_data);
        Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
        //String cursorThumb = cursor.getString(thum);
        String fileName = FilenameUtils.getBaseName(absolutePathThumb);
        String extension = FilenameUtils.getExtension(absolutePathThumb);
        String duration = getDuration(absolutePathThumb);
        VideoModel videoModel = new VideoModel();
        videoModel.setDuration(duration);
        videoModel.setVideo_uri(thumbUri.toString());
        videoModel.setVideo_path(absolutePathThumb);
        videoModel.setVideo_name(fileName);
        videoModel.setVideo_thumb(cursor.getString(thum));
        if (extension!=null){
            videoModel.setVideo_extension(extension);
        }else {
            videoModel.setVideo_extension("mp4");
        }
        if (duration!=null){
            videoModel.setDuration(duration);
        }else {
            videoModel.setDuration("00:00");
        }
        arrayListVideos.add(videoModel);
    }
    
    videoAdapter = new VideoAdapter(this,arrayListVideos);
    shimmerFrameLayout.setVisibility(View.INVISIBLE);
    shimmerFrameLayout.stopShimmer();
    recyclerView.setVisibility(View.VISIBLE);
    recyclerView.setAdapter(videoAdapter);
    //set adapter
}


}

VideoAdapter:

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoAdapterViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;

Context context;
ArrayList<VideoModel> arrayListVideo;
ArrayList<VideoModel> arrayListVideoAll;
private Activity mainActivity;

public VideoAdapter(Context context, ArrayList<VideoModel> arrayListVideos){
    this.context = context;
    this.arrayListVideo = arrayListVideos;
    arrayListVideoAll = new ArrayList<>(arrayListVideo);
    mainActivity = (Activity) context;
}

@NonNull
@Override
public VideoAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    switch (i){
        case UNIFIED_NATIVE_AD_VIEW_TYPE:
            View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified,viewGroup,false);
            return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
        case MENU_ITEM_VIEW_TYPE:
        default:
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos,viewGroup,false);
            return new VideoAdapterViewHolder(view);
    }
}

@Override
public void onBindViewHolder(@NonNull VideoAdapterViewHolder videoAdapterViewHolder, int i) {
    int viewType = getItemViewType(i);
    switch (viewType){
        case UNIFIED_NATIVE_AD_VIEW_TYPE:
            UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd)arrayListVideo.get(i);
            populateNativeAdView(unifiedNativeAd,((UnifiedNativeAdViewHolder)videoAdapterViewHolder).getAdView());
            break;
        case MENU_ITEM_VIEW_TYPE:
            Glide.with(context).load(arrayListVideo.get(i).getVideo_thumb()).into(videoAdapterViewHolder.image);
            videoAdapterViewHolder.name.setText(arrayListVideo.get(i).getVideo_name() + "." + arrayListVideo.get(i).getVideo_extension());
            videoAdapterViewHolder.duration.setText(arrayListVideo.get(i).getDuration());
    }
}

@Override
public int getItemCount() {
    return arrayListVideo.size();
}

public class VideoAdapterViewHolder extends RecyclerView.ViewHolder{
    public ImageView image;
    public TextView name,duration;
    public ImageView videoOption;

    public VideoAdapterViewHolder(@NonNull View itemView) {
        super(itemView);
        if (!(itemView instanceof AdView)) {
            image = (ImageView)itemView.findViewById(R.id.vid_image);
            name = (TextView)itemView.findViewById(R.id.vid_name);
            duration = (TextView)itemView.findViewById(R.id.vid_duration);
            videoOption = (ImageView) itemView.findViewById(R.id.video_option);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
                    ((MainActivity)context).openVideoPlayerActivity(videoModel);
                }
            });
            videoOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
                    ((MainActivity)context).VideoMoreOption(videoModel);
                }
            });
        }
    }
}

private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
    ((TextView)adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
    ((TextView)adView.getBodyView()).setText(unifiedNativeAd.getBody());
    ((TextView)adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());

    NativeAd.Image icon = unifiedNativeAd.getIcon();
    if (icon==null){
        adView.getIconView().setVisibility(View.INVISIBLE);
    }else {
        ((ImageView)adView.getIconView()).setImageDrawable(icon.getDrawable());
        adView.getIconView().setVisibility(View.VISIBLE);
    }

    if(unifiedNativeAd.getPrice()==null){
        adView.getPriceView().setVisibility(View.INVISIBLE);
    }else {
        adView.getPriceView().setVisibility(View.VISIBLE);
        ((TextView)adView.getPriceView()).setText(unifiedNativeAd.getPrice());
    }

    if(unifiedNativeAd.getStarRating()==null){
        adView.getStarRatingView().setVisibility(View.INVISIBLE);
    }else {
        adView.getStarRatingView().setVisibility(View.VISIBLE);
        ((RatingBar)adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
    }

    if(unifiedNativeAd.getAdvertiser()==null){
        adView.getAdvertiserView().setVisibility(View.INVISIBLE);
    }else {
        adView.getAdvertiserView().setVisibility(View.VISIBLE);
        ((TextView)adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
    }

    adView.setNativeAd(unifiedNativeAd);
}

}


回答1:


public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;

Context context;
ArrayList<Object> arrayListVideo;
ArrayList<Object> arrayListVideoAll;
private Activity mainActivity;

public VideoAdapter(Context context, ArrayList<Object> arrayListVideos) {
    this.context = context;
    this.arrayListVideo = arrayListVideos;
    arrayListVideoAll = new ArrayList<>(arrayListVideo);
    mainActivity = (Activity) context;
}
@Override
public int getItemViewType(int position) {
    if(arrayListVideo.get(position) instanceof VideoModel){
        return MENU_ITEM_VIEW_TYPE;
    } else{
        return UNIFIED_NATIVE_AD_VIEW_TYPE;
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    switch (i) {
        case UNIFIED_NATIVE_AD_VIEW_TYPE:
            View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified, viewGroup, false);
            return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
        case MENU_ITEM_VIEW_TYPE:
        default:
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos, viewGroup, false);
            return new VideoAdapterViewHolder(view);
    }
}


@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
    switch (viewHolder.getItemViewType()) {
        case UNIFIED_NATIVE_AD_VIEW_TYPE:
            UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd) arrayListVideo.get(i);
            populateNativeAdView(unifiedNativeAd, ((UnifiedNativeAdViewHolder) viewHolder).getAdView());
            break;
        case MENU_ITEM_VIEW_TYPE:
            final VideoAdapterViewHolder videoAdapterViewHolder = (VideoAdapterViewHolder) viewHolder;
            final VideoModel item = (VideoModel) arrayListVideo.get(i);
            Glide.with(context).load(item.getVideo_thumb()).into(videoAdapterViewHolder.image);

            videoAdapterViewHolder.name.setText(item.getVideo_name() +
                    "." + item.getVideo_extension());
            videoAdapterViewHolder.duration.setText(item.getDuration());
    }
}

@Override
public int getItemCount() {
    return arrayListVideo.size();
}

@Override
public Filter getFilter() {
    return null;
}

public class VideoAdapterViewHolder extends RecyclerView.ViewHolder {
    public ImageView image;
    public TextView name, duration;
    public ImageView videoOption;

    public VideoAdapterViewHolder(@NonNull View itemView) {
        super(itemView);
        if (!(itemView instanceof AdView)) {
            image = (ImageView) itemView.findViewById(R.id.vid_image);
            name = (TextView) itemView.findViewById(R.id.vid_name);
            duration = (TextView) itemView.findViewById(R.id.vid_duration);
            videoOption = (ImageView) itemView.findViewById(R.id.video_option);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
                    ((MainActivity) context).openVideoPlayerActivity(videoModel);
                }
            });
            videoOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
                    ((MainActivity) context).VideoMoreOption(videoModel);
                }
            });
        }
    }
}

private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
    ((TextView) adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
    ((TextView) adView.getBodyView()).setText(unifiedNativeAd.getBody());
    ((TextView) adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());

    NativeAd.Image icon = unifiedNativeAd.getIcon();
    if (icon == null) {
        adView.getIconView().setVisibility(View.INVISIBLE);
    } else {
        ((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
        adView.getIconView().setVisibility(View.VISIBLE);
    }

    if (unifiedNativeAd.getPrice() == null) {
        adView.getPriceView().setVisibility(View.INVISIBLE);
    } else {
        adView.getPriceView().setVisibility(View.VISIBLE);
        ((TextView) adView.getPriceView()).setText(unifiedNativeAd.getPrice());
    }

    if (unifiedNativeAd.getStarRating() == null) {
        adView.getStarRatingView().setVisibility(View.INVISIBLE);
    } else {
        adView.getStarRatingView().setVisibility(View.VISIBLE);
        ((RatingBar) adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
    }

    if (unifiedNativeAd.getAdvertiser() == null) {
        adView.getAdvertiserView().setVisibility(View.INVISIBLE);
    } else {
        adView.getAdvertiserView().setVisibility(View.VISIBLE);
        ((TextView) adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
    }

    adView.setNativeAd(unifiedNativeAd);
}

}

MainActivity

public class MainActivity extends AppCompatActivity {

public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;

@BindView(R.id.recyclerView)
RecyclerView recyclerView;

ArrayList<Object> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());

    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    adMob();
    arrayListVideos = new ArrayList<>();

    mLayoutManager = new GridLayoutManager(this, autoCardWith);
    //mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    // @Override
    //public int getSpanSize(int position) {  if (position % MainActivity.ITEMS_PER_AD == 0) {  return autoCardWith; } return 1;      }
    //});
    recyclerView.setHasFixedSize(true);
    //recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
    recyclerView.setHasFixedSize(true);
    shimmerFrameLayout = findViewById(R.id.shimmer_view);
    shimmerFrameLayout.setVisibility(View.VISIBLE);
    shimmerFrameLayout.startShimmer();
    recyclerView.setVisibility(View.INVISIBLE);

    askPermission();

    displayAllVideos();

    loadNativeAds();

}

private void loadNativeAds() {
    AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));

    adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
        @Override
        public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
            nativeAds.add(unifiedNativeAd);
            if (!adLoader.isLoading()) {
                insertAdsinMenuItem();
            }
        }
    }).withAdListener(new AdListener() {
        @Override
        public void onAdFailedToLoad(int i) {
            super.onAdFailedToLoad(i);
            if (!adLoader.isLoading()) {
                insertAdsinMenuItem();
            }
        }
    }).build();

    adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}

private void insertAdsinMenuItem() {
    if (nativeAds.size() < 0 ){
        return;
    }
    int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
    int index = 0;

    for (UnifiedNativeAd ad:nativeAds){
        arrayListVideos.add(index,ad);
        index = index + offset;
    }

}

private void adMob() {
    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
        }
    });
    mAdView = findViewById(R.id.main_banner);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}

private void askPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:"+getPackageName()));
        startActivityForResult(intent,2084);
    }
}

private void displayAllVideos() {
    Uri uri;
    Cursor cursor;
    int column_index_data,thum;

    String absolutePathThumb;
    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};

    final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
    cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

    while (cursor.moveToNext()){
        Log.d("VIDEO", cursor.getString(0));
        absolutePathThumb = cursor.getString(column_index_data);
        Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
        //String cursorThumb = cursor.getString(thum);
        String fileName = FilenameUtils.getBaseName(absolutePathThumb);
        String extension = FilenameUtils.getExtension(absolutePathThumb);
        String duration = getDuration(absolutePathThumb);
        VideoModel videoModel = new VideoModel();
        videoModel.setDuration(duration);
        videoModel.setVideo_uri(thumbUri.toString());
        videoModel.setVideo_path(absolutePathThumb);
        videoModel.setVideo_name(fileName);
        videoModel.setVideo_thumb(cursor.getString(thum));
        if (extension!=null){
            videoModel.setVideo_extension(extension);
        }else {
            videoModel.setVideo_extension("mp4");
        }
        if (duration!=null){
            videoModel.setDuration(duration);
        }else {
            videoModel.setDuration("00:00");
        }
        arrayListVideos.add(videoModel);
    }

    videoAdapter = new VideoAdapter(this,arrayListVideos);
    shimmerFrameLayout.setVisibility(View.INVISIBLE);
    shimmerFrameLayout.stopShimmer();
    recyclerView.setVisibility(View.VISIBLE);
    recyclerView.setAdapter(videoAdapter);
    //set adapter
}
}


来源:https://stackoverflow.com/questions/62983638/unable-to-initialize-native-ad-inside-recyclerview-in-androidx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!