clockbyte / admobadapter

It wraps your Adapter to display Admob native ads and banners in a ListView/RecyclerView data set. It based on the Yahoo fetchr project https://github.com/yahoo/fetchr
Apache License 2.0
237 stars 75 forks source link

need help #97

Closed NikiHard closed 6 years ago

NikiHard commented 6 years ago

Hello, I need help screenshot_1507760863


public class LatestFragment extends Fragment {

    @BindView(R2.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R2.id.swipe)
    SwipeRefreshLayout mSwipe;
    @BindView(R2.id.progress)
    MaterialProgressBar mProgress;

    private List<Wallpaper> mWallpapers;
    private LatestAdapter mAdapter;
    private AsyncTask mAsyncTask;
    private StaggeredGridLayoutManager mManager;
    AdmobExpressRecyclerAdapterWrapper adapterWrapper;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_latest, container, false);
        ButterKnife.bind(this, view);

    return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mManager = new StaggeredGridLayoutManager(
                getActivity().getResources().getInteger(R.integer.latest_wallpapers_column_count),
                StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(mManager);
        mRecyclerView.setHasFixedSize(false);

        mSwipe.setColorSchemeColors(ColorHelper.getAttributeColor(
                getActivity(), R.attr.colorAccent));
        mSwipe.setOnRefreshListener(() -> {
            if (mAsyncTask != null) {
                mSwipe.setRefreshing(false);
                return;
            }

            WallpapersLoaderTask.start(getActivity());
            prepareLatestWallpapers();
        });
        MobileAds.initialize(getActivity(), "ca-app-pub-##########");

        resetRecyclerViewPadding();
        resetViewBottomPadding(mRecyclerView, true);

        prepareLatestWallpapers();

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mAsyncTask != null) return;
        if (mAdapter == null) return;

        int[] positions = mManager.findFirstVisibleItemPositions(null);

        int spanCount = getActivity().getResources().getInteger(
                R.integer.latest_wallpapers_column_count);
        ViewHelper.resetSpanCount(mRecyclerView, spanCount);
        resetRecyclerViewPadding();
        resetViewBottomPadding(mRecyclerView, true);

        mAdapter = new LatestAdapter(getActivity(), mWallpapers);
        //LatestAdapter adapter  = new LatestAdapter(getActivity(), mWallpapers);

///*
        adapterWrapper = AdmobExpressRecyclerAdapterWrapper.builder(getActivity())
                .setLimitOfAds(1)
                .setFirstAdIndex(5)
                .setNoOfDataBetweenAds(3)
                //.setAdSize(new AdSize(AdSize.FULL_WIDTH,150))
                //.setAdsUnitId(getString(R.string.test_admob_unit_id))
                //.setTestDeviceIds(testDevicesIds)
                .setAdapter(mAdapter)
                .setAdViewWrappingStrategy(new AdViewWrappingStrategyBase() {
                    @NonNull
                    @Override
                    protected ViewGroup getAdViewWrapper(ViewGroup parent) {
                        return (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.native_express_ad_container,
                                parent, false);
                    }

                    @Override
                    protected void recycleAdViewWrapper(@NonNull ViewGroup wrapper, @NonNull NativeExpressAdView ad) {
                        //get the view which directly will contain ad
                        ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container);
                        //iterating through all children of the container view and remove the first occured {@link NativeExpressAdView}. It could be different with {@param ad}!!!*//*
                        for (int i = 0; i < container.getChildCount(); i++) {
                            View v = container.getChildAt(i);
                            if (v instanceof NativeExpressAdView) {
                                container.removeViewAt(i);
                                break;
                            }
                        }
                    }

                    @Override
                    protected void addAdViewToWrapper(@NonNull ViewGroup wrapper, @NonNull NativeExpressAdView ad) {
                        //get the view which directly will contain ad
                        ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container);
                        //add the {@param ad} directly to the end of container*//*
                        container.addView(ad);
                    }
                })
                .build();

        mRecyclerView.setAdapter(adapterWrapper);
   //     */

       // mRecyclerView.setAdapter(mAdapter);

        if (positions.length > 0)
            mRecyclerView.scrollToPosition(positions[0]);
    }

    @Override
    public void onDestroy() {
        if (mAsyncTask != null) {
            mAsyncTask.cancel(true);
        }
        super.onDestroy();
        //adapterWrapper.release();
    }

    private void resetRecyclerViewPadding() {
        int spanCount = getActivity().getResources().getInteger(
                R.integer.latest_wallpapers_column_count);
        if (spanCount == 1) {
            mRecyclerView.setPadding(0, 0, 0, 0);
            return;
        }

        if (WallpaperBoardApplication.getConfiguration().getWallpapersGrid() ==
                WallpaperBoardApplication.GridStyle.FLAT) {
            int padding = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin);
            mRecyclerView.setPadding(padding, padding, 0, 0);
            return;
        }

        int paddingTop = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin_top);
        int paddingLeft = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin_right);
        mRecyclerView.setPadding(paddingLeft, paddingTop, 0, 0);
    }

    private void prepareLatestWallpapers() {
        mAsyncTask = new AsyncTask<Void, Integer, Boolean>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (!mSwipe.isRefreshing()) {
                    mProgress.setVisibility(View.VISIBLE);
                }
            }

            @Override
            protected Boolean doInBackground(Void... voids) {
                while (!isCancelled()) {
                    try {
                        Thread.sleep(1);
                        mWallpapers = Database.get(getActivity()).getLatestWallpapers();

                        for (int i = 0; i < mWallpapers.size(); i++) {
                            publishProgress(i);
                        }
                        return true;
                    } catch (Exception e) {
                        LogUtil.e(Log.getStackTraceString(e));
                        return false;
                    }
                }
                return false;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                new WallpaperDimensionLoader(values[0]).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                mAsyncTask = null;
            }
        }.execute();
    }

    private class WallpaperDimensionLoader extends AsyncTask<Void, Void, Boolean> {

        private int mPosition;

        private WallpaperDimensionLoader(int position) {
            mPosition = position;

        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    if (mWallpapers.get(mPosition).getDimensions() != null)
                        return true;

                    URL url = new URL(mWallpapers.get(mPosition).getUrl());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000);

                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream stream = connection.getInputStream();

                        final BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeStream(stream, null, options);

                        ImageSize imageSize = new ImageSize(options.outWidth, options.outHeight);
                        mWallpapers.get(mPosition).setDimensions(imageSize);

                        Database.get(getActivity()).updateWallpaper(
                                mWallpapers.get(mPosition));
                        stream.close();
                        return true;
                    }
                    return false;
                } catch (Exception e) {
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (getActivity() == null) {
                LogUtil.e("WallpaperDimensionLoader: error activity is null");
                return;
            }
            if (getActivity().isFinishing()) {
                LogUtil.e("WallpaperDimensionLoader: error activity is finishing");
                return;
            }

            if (aBoolean) {
                if (mPosition == (mWallpapers.size() - 1)) {
                    if (mSwipe.isRefreshing()) {
                        mAdapter.setWallpapers(mWallpapers);
                    } else {
                        mAdapter = new LatestAdapter(getActivity(), mWallpapers);
///*
                        adapterWrapper = AdmobExpressRecyclerAdapterWrapper.builder(getActivity())
                                .setLimitOfAds(1)
                                .setFirstAdIndex(5)
                                .setNoOfDataBetweenAds(3)
                                //.setAdSize(new AdSize(AdSize.FULL_WIDTH,150))
                                //.setAdsUnitId(getString(R.string.test_admob_unit_id))
                                //.setTestDeviceIds(testDevicesIds)
                                .setAdapter(mAdapter)
                                .setAdViewWrappingStrategy(new AdViewWrappingStrategyBase() {
                                    @NonNull
                                    @Override
                                    protected ViewGroup getAdViewWrapper(ViewGroup parent) {
                                        return (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.native_express_ad_container,
                                                parent, false);
                                    }

                                    @Override
                                    protected void recycleAdViewWrapper(@NonNull ViewGroup wrapper, @NonNull NativeExpressAdView ad) {
                                        //get the view which directly will contain ad
                                        ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container);
                                        //iterating through all children of the container view and remove the first occured {@link NativeExpressAdView}. It could be different with {@param ad}!!!*//*
                                        for (int i = 0; i < container.getChildCount(); i++) {
                                            View v = container.getChildAt(i);
                                            if (v instanceof NativeExpressAdView) {
                                                container.removeViewAt(i);
                                                break;
                                            }
                                        }
                                    }

                                    @Override
                                    protected void addAdViewToWrapper(@NonNull ViewGroup wrapper, @NonNull NativeExpressAdView ad) {
                                        //get the view which directly will contain ad
                                        ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container);
                                        //add the {@param ad} directly to the end of container*//*
                                        container.addView(ad);
                                    }
                                })
                                .build();

                        mRecyclerView.setAdapter(adapterWrapper);
                       // */

                         //mRecyclerView.setAdapter(mAdapter);

                    }

                    mSwipe.setRefreshing(false);
                    mProgress.setVisibility(View.GONE);

                }
            } else {
                mSwipe.setRefreshing(false);
                mProgress.setVisibility(View.GONE);
            }

        }

    }
}
kot331107 commented 6 years ago

@NikiHard Hi, see https://github.com/clockbyte/admobadapter/wiki/Cookbook#in-case-you-stucked-with-getting-the-correct-itemindex-of-a-source-collection-in-a-listviewrecyclerview-click-handler I guess it should make sense how to handle indices in your case. Pls provide a code which handles a click event.

NikiHard commented 6 years ago
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.ViewHolder> {

    private final Context mContext;
    private List<Wallpaper> mWallpapers;
    private final DisplayImageOptions.Builder mOptions;
    // A Native Express ad is placed in every nth position in the RecyclerView.

    public LatestAdapter(@NonNull Context context, @NonNull List<Wallpaper> wallpapers) {
        mContext = context;
        mWallpapers = wallpapers;

        mOptions = ImageConfig.getRawDefaultImageOptions();
        mOptions.resetViewBeforeLoading(true);
        mOptions.cacheInMemory(true);
        mOptions.cacheOnDisk(true);
        mOptions.displayer(new FadeInBitmapDisplayer(700));

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.fragment_latest_item_grid, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Wallpaper wallpaper = mWallpapers.get(position);
        holder.name.setText(wallpaper.getName());
        holder.author.setText(wallpaper.getAuthor());

        if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
            holder.download.setVisibility(View.VISIBLE);
        } else {
            holder.download.setVisibility(View.GONE);
        }

        setFavorite(holder.favorite, Color.WHITE, position, false);
        resetImageViewHeight(holder.image, wallpaper.getDimensions());

        ImageLoader.getInstance().displayImage(
                wallpaper.getThumbUrl(),
                new ImageViewAware(holder.image),
                mOptions.build(),
                ImageConfig.getBigThumbnailSize(),
                new SimpleImageLoadingListener() {

                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        super.onLoadingStarted(imageUri, view);
                        int color;
                        if (wallpaper.getColor() == 0) {
                            color = ColorHelper.getAttributeColor(
                                    mContext, R.attr.card_background);
                        } else {
                            color = wallpaper.getColor();
                        }

                        holder.card.setCardBackgroundColor(color);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        if (loadedImage != null && wallpaper.getColor() == 0) {
                            Palette.from(loadedImage).generate(palette -> {
                                int vibrant = ColorHelper.getAttributeColor(
                                        mContext, R.attr.card_background);
                                int color = palette.getVibrantColor(vibrant);
                                if (color == vibrant)
                                    color = palette.getMutedColor(vibrant);
                                holder.card.setCardBackgroundColor(color);

                                wallpaper.setColor(color);
                                Database.get(mContext).updateWallpaper(wallpaper);
                            });
                        }
                    }
                },
                null);
    }

    @Override
    public int getItemCount() {
        //RecyclerExampleAdapter adapter  = new RecyclerExampleAdapter(this);

        return mWallpapers.size();
    }

    private void resetImageViewHeight(@NonNull ImageView imageView, ImageSize imageSize) {
        if (imageSize == null) imageSize = new ImageSize(400, 300);

        int width = WindowHelper.getScreenSize(mContext).x;
        int spanCount = mContext.getResources().getInteger(R.integer.latest_wallpapers_column_count);
        if (spanCount > 1) {
            width = width/spanCount;
        }
        double scaleFactor = (double) width / (double) imageSize.getWidth();
        double measuredHeight = (double) imageSize.getHeight() * scaleFactor;
        imageView.getLayoutParams().height = Double.valueOf(measuredHeight).intValue();
        imageView.requestLayout();

    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @BindView(R2.id.image)
        ImageView image;
        @BindView(R2.id.name)
        TextView name;
        @BindView(R2.id.author)
        TextView author;
        @BindView(R2.id.favorite)
        ImageView favorite;
        @BindView(R2.id.download)
        ImageView download;
        @BindView(R2.id.apply)
        ImageView apply;
        @BindView(R2.id.card)
        CardView card;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            if (mContext.getResources().getInteger(R.integer.latest_wallpapers_column_count) == 1) {
                if (card.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
                    StaggeredGridLayoutManager.LayoutParams params =
                            (StaggeredGridLayoutManager.LayoutParams) card.getLayoutParams();
                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    params.topMargin = 0;
                    params.bottomMargin = 0;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        params.setMarginEnd(0);
                    }
                }
            } else {
                setCardViewToFlat(card);
            }

            if (!Preferences.get(mContext).isShadowEnabled()) {
                card.setCardElevation(0f);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                StateListAnimator stateListAnimator = AnimatorInflater
                        .loadStateListAnimator(mContext, R.animator.card_lift);
                card.setStateListAnimator(stateListAnimator);
            }

            if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
                download.setImageDrawable(DrawableHelper.getTintedDrawable(
                        mContext, R.drawable.ic_toolbar_download, Color.WHITE));
                download.setOnClickListener(this);
            }

            apply.setImageDrawable(DrawableHelper.getTintedDrawable(
                    mContext, R.drawable.ic_toolbar_apply_options, Color.WHITE));

            card.setOnClickListener(this);
            favorite.setOnClickListener(this);
            apply.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {
            int id = view.getId();
            int position = getAdapterPosition();
            if (position < 0 || position > mWallpapers.size()) return;

            if (id == R.id.favorite) {
                boolean isFavorite = mWallpapers.get(position).isFavorite();
                Database.get(mContext).favoriteWallpaper(
                        mWallpapers.get(position).getUrl(), !isFavorite);

                mWallpapers.get(position).setFavorite(!isFavorite);
                setFavorite(favorite, name.getCurrentTextColor(), position, true);

                CafeBar.builder(mContext)
                        .theme(CafeBarTheme.Custom(ColorHelper.getAttributeColor(
                                mContext, R.attr.card_background)))
                        .fitSystemWindow()
                        .floating(true)
                        .typeface(TypefaceHelper.getRegular(mContext), TypefaceHelper.getBold(mContext))
                        .content(String.format(
                                mContext.getResources().getString(mWallpapers.get(position).isFavorite() ?
                                        R.string.wallpaper_favorite_added : R.string.wallpaper_favorite_removed),
                                mWallpapers.get(position).getName()))
                        .icon(mWallpapers.get(position).isFavorite() ?
                                R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove)
                        .show();
            } else if (id == R.id.download) {
                if (PermissionHelper.isStorageGranted(mContext)) {
                    WallpaperDownloader.prepare(mContext)
                            .wallpaper(mWallpapers.get(position))
                            .start();
                    return;
                }

                PermissionHelper.requestStorage(mContext);
            } else if (id == R.id.apply) {
                Popup popup = Popup.Builder(mContext)
                        .to(apply)
                        .list(PopupItem.getApplyItems(mContext))
                        .callback((applyPopup, i) -> {
                            PopupItem item = applyPopup.getItems().get(i);
                            if (item.getType() == PopupItem.Type.WALLPAPER_CROP) {
                                Preferences.get(mContext).setCropWallpaper(!item.getCheckboxValue());
                                item.setCheckboxValue(Preferences.get(mContext).isCropWallpaper());

                                applyPopup.updateItem(i, item);
                                return;
                            } else if (item.getType() == PopupItem.Type.LOCKSCREEN) {
                                WallpaperApplyTask.prepare(mContext)
                                        .wallpaper(mWallpapers.get(position))
                                        .to(WallpaperApplyTask.Apply.LOCKSCREEN)
                                        .start(AsyncTask.THREAD_POOL_EXECUTOR);
                            } else if (item.getType() == PopupItem.Type.HOMESCREEN) {
                                WallpaperApplyTask.prepare(mContext)
                                        .wallpaper(mWallpapers.get(position))
                                        .to(WallpaperApplyTask.Apply.HOMESCREEN)
                                        .start(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                            applyPopup.dismiss();
                        })
                        .build();

                if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
                    popup.removeItem(popup.getItems().size() - 1);
                }

                popup.show();
            } else if (id == R.id.card) {
                if (WallpapersAdapter.sIsClickable) {
                    WallpapersAdapter.sIsClickable = false;
                    try {
                        Bitmap bitmap = null;
                        if (image.getDrawable() != null) {
                            bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
                        }

                        final Intent intent = new Intent(mContext, WallpaperBoardPreviewActivity.class);
                        intent.putExtra(Extras.EXTRA_URL, mWallpapers.get(position).getUrl());

                        ActivityTransitionLauncher.with((AppCompatActivity) mContext)
                                .from(image, Extras.EXTRA_IMAGE)
                                .image(bitmap)
                                .launch(intent);
                    } catch (Exception e) {
                        WallpapersAdapter.sIsClickable = true;
                    }
                }
            }

        }
    }

    public void setWallpapers(@NonNull List<Wallpaper> wallpapers) {
        mWallpapers = wallpapers;
        notifyDataSetChanged();
    }

    private void setFavorite(@NonNull ImageView imageView, @ColorInt int color, int position, boolean animate) {
        if (position < 0 || position > mWallpapers.size()) return;

        boolean isFavorite = mWallpapers.get(position).isFavorite();

        if (animate) {
            AnimationHelper.show(imageView)
                    .interpolator(new LinearOutSlowInInterpolator())
                    .callback(new AnimationHelper.Callback() {
                        @Override
                        public void onAnimationStart() {
                            imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,
                                    isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));
                        }

                        @Override
                        public void onAnimationEnd() {

                        }
                    })
                    .start();
            return;
        }

        imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,
                isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));
    }
}
kot331107 commented 6 years ago

@NikiHard

int position = getAdapterPosition();

Pls provide getAdapterPosition() also

kot331107 commented 6 years ago

@NikiHard does it mean you have found a solution yourself?

NikiHard commented 6 years ago

It turned out like this in AdmobAdapterCalculator

     * Исправил смещение обоев при отображении рекламы, вдруг еще где понадобится
     */
    public int getAdsCountToPublish(int fetchedAdsCount, int sourceItemsCount){
       // if(fetchedAdsCount <= 0 || getNoOfDataBetweenAds() <= 0) return 0;
        int expected = 0;
        //if(sourceItemsCount > 0 && sourceItemsCount >= getOffsetValue()+1)
        //    expected = (sourceItemsCount - getOffsetValue()) / getNoOfDataBetweenAds() + 1;
        //expected = Math.max(0, expected);
        expected =0;
        return Math.min(expected, getLimitOfAds());
    }

I just don't understand much about the development under android and did not quite understand that I needed to show you more

NikiHard commented 6 years ago

there is still such a problem, but elsewhere screenshot_1508179862