5

I've been working in RecyclerView and Google Volley for parsing JSON. Then I added google native ads!

I following tutorial on this link

So I did change the RecyclerViewAdapter like google developers guideline!

It says that the List has to be a List of Object (List) So I changed this and a few other things in the Adapter!

Then Android Studio shows no Errors and I'm able to launch the Application. But when I'm going to open the Fragment with the mentioned RecyclerView it crashes.

It says:

java.lang.ClassCastException: com.graciaapps.nameoncards.instance.greetoptions.SubOptionOneInstance cannot be cast to com.google.android.gms.ads.NativeExpressAdView

This is the following line onBindViewHolder

NativeExpressAdView adView =(NativeExpressAdView)greetingInstanceList.get(position);

FirstFragment.java

public class FirstFragment extends Fragment {
    RecyclerView recyclerView;
    List<Object> subOptionOneInstanceList = new ArrayList<Object>();
    View viewMain;
    Bitmap rectBitmap,squareBitmap;
    int countOfBitmap;
    private String TAG = getClass().getName();
    public String mainCategory,mainTitle;
    SwipeRefreshLayout srl_first_fragment;
    String JSON_TAG_CATEGORY = "";

//    NATIVE EXPRESS ADS
    public static final int ITEMS_PER_AD = 8;
    private static final int NATIVE_EXPRESS_AD_HEIGHT = 150;
    // The Native Express ad unit ID.
    public static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1072772517";

    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        viewMain = inflater.inflate(R.layout.fragment_first, container, false);

        setReference();
        checkConnection();

        return viewMain;
    }

    private void setReference() {
        srl_first_fragment = (SwipeRefreshLayout) viewMain.findViewById(R.id.srl_first_fragment);
        srl_first_fragment.setColorSchemeColors(ContextCompat.getColor(getActivity(),R.color.colorPrimary));
//        progressDialog = new ProgressDialog(getContext(),"Processing..",R.color.colorPrimary);
    }

    private void checkConnection() {
        boolean isConnected = EndPoints.isHavingNetworkConnection(getActivity());
        if(!isConnected)
        {
            if(srl_first_fragment != null) {
                if (srl_first_fragment.isRefreshing()) {
                    srl_first_fragment.setRefreshing(false);
                }
            }
            Snackbar.make(viewMain,"Not Connected to internet.",Snackbar.LENGTH_INDEFINITE).setAction("Try Again", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkConnection();
                }
            }).setActionTextColor(Color.RED).show();
        }
        else
        {
            srl_first_fragment.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    checkConnection();
                    subOptionOneInstanceList.clear();
//                    subOptionOneAdapter.notifyDataSetChanged();
                    if(mainCategory.equals(getString(R.string.birthday)) && mainTitle.equals("Greetings"))
                    {
                        sendBirthdayGreetingRequest();
                        JSON_TAG_CATEGORY = "birthday_greetings";
                    }
                    if(mainCategory.equals(getString(R.string.wedding)) && mainTitle.equals("Greetings"))
                    {
                        sendWeddingGreetingRequest();
                        JSON_TAG_CATEGORY = "wedding_greetings";
                    }
                }
            });


            RecyclerView.LayoutManager gridLayoutManager = new  GridLayoutManager(getActivity(),2,LinearLayoutManager.VERTICAL,false);
//            gridLayoutManager.scrollToPositionWithOffset(1,0);
            recyclerView = (RecyclerView) viewMain.findViewById(R.id.rvFirstFragment);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(gridLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());

//            progressDialog.setCanceledOnTouchOutside(false);
//            progressDialog.setCancelable(false);

            try {
                Log.d(TAG,"SELECTED CATEGORY FOR FIRST FRAGMENT"+getActivity().getIntent().getExtras().getString("category"));
                Log.d(TAG,"SELECTED CATEGORY FOR FIRST FRAGMENT"+ EndPoints.CATEGORY_ONE);
                mainCategory = getActivity().getIntent().getExtras().getString("category");
                mainTitle = EndPoints.CATEGORY_ONE;
                if(mainCategory.equals(getString(R.string.birthday)) && mainTitle.equals("Greetings"))
                {
                    sendBirthdayGreetingRequest();
                    JSON_TAG_CATEGORY = "birthday_greetings";
                }
                if(mainCategory.equals(getString(R.string.wedding)) && mainTitle.equals("Greetings"))
                {
                    sendWeddingGreetingRequest();
                    JSON_TAG_CATEGORY = "wedding_greetings";
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            addNativeExpressAds();
            setUpAndLoadNativeExpressAds();

            RecyclerView.Adapter subOptionOneAdapter = new SubOptionOneAdapter(getActivity(),subOptionOneInstanceList);
            recyclerView.setAdapter(subOptionOneAdapter);
        }
    }

    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 = 0; i <= subOptionOneInstanceList.size(); i += ITEMS_PER_AD) {
            final NativeExpressAdView adView = new NativeExpressAdView(this.getContext());
            subOptionOneInstanceList.add(i, adView);
        }
    }

    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.
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                final float scale = getActivity().getResources().getDisplayMetrics().density;
                // Set the ad size and ad unit ID for each Native Express ad in the items list.
                for (int i = 0; i <= subOptionOneInstanceList.size(); i += ITEMS_PER_AD) {
                    final NativeExpressAdView adView = (NativeExpressAdView) subOptionOneInstanceList.get(i);
                    final CardView cardView = (CardView) getActivity().findViewById(R.id.ad_card_view);
                    final int adWidth = cardView.getWidth() - cardView.getPaddingLeft() - cardView.getPaddingRight();
                    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(0);
            }
        });
    }

    private void loadNativeExpressAd(final int index) {

        if (index >= subOptionOneInstanceList.size()) {
            return;
        }

        Object item = subOptionOneInstanceList.get(index);
        if (!(item instanceof NativeExpressAdView)) {
            throw new ClassCastException("Expected item at index " + index + " to be a Native" + " Express ad.");
        }

        final NativeExpressAdView adView = (NativeExpressAdView) item;

        // Set an AdListener on the NativeExpressAdView to wait for the previous Native Express ad
        // to finish loading before loading the next ad in the items list.
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                // The previous Native Express ad loaded successfully, call this method again to
                // load the next ad in the items list.
                loadNativeExpressAd(index + ITEMS_PER_AD);
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // The previous Native Express ad failed to load. Call this method again to load
                // the next ad in the items list.
                Log.e("MainActivity", "The previous Native Express ad failed to load. Attempting to"
                        + " load the next Native Express ad in the items list.");
                loadNativeExpressAd(index + ITEMS_PER_AD);
            }
        });

        // Load the Native Express ad.
        adView.loadAd(new AdRequest.Builder().build());
    }

    private void sendBirthdayGreetingRequest() {
        StringRequest stringRequest = new StringRequest(EndPoints.BIRTHDAY_GREETINGS_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                showJSON(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG,"ERROR IN RESPONSE"+error.getMessage());
                if(srl_first_fragment.isRefreshing())
                {
                    srl_first_fragment.setRefreshing(false);
                }
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    private void sendWeddingGreetingRequest() {
        StringRequest stringRequest = new StringRequest(EndPoints.WEDDING_GREETINGS_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                showJSON(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG,"ERROR IN RESPONSE"+error.getMessage());
                if(srl_first_fragment.isRefreshing())
                {
                    srl_first_fragment.setRefreshing(false);
                }
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    private void showJSON(String response) {
        Log.d(TAG, "RESPONSE" + response);
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray(JSON_TAG_CATEGORY);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonInnerObject = jsonArray.getJSONObject(i);

                Log.d(TAG, "ID WOULD BE                     " + jsonInnerObject.getInt(EndPoints.TAG_ID));
                Log.d(TAG, "CATEGORY WOULD BE               " + jsonInnerObject.getString(EndPoints.TAG_CATEGORY));
                Log.d(TAG, "IS FRAME WOULD BE               " + jsonInnerObject.getString(EndPoints.TAG_ISFRAME));
                Log.d(TAG, "ORIGINAL IMAGE URL WOULD BE     " + jsonInnerObject.getString(EndPoints.TAG_ORIGINAL_IMAGE_URL));
                Log.d(TAG, "SAMPLE IMAGE URL WOULD BE       " + jsonInnerObject.getString(EndPoints.TAG_SAMPLE_IMAGE_URL));
                Log.d(TAG, "FONT STYLE WOULD BE             " + jsonInnerObject.getString(EndPoints.TAG_FONT_STYLE));
                Log.d(TAG, "FONT COLOR WOULD BE             " + jsonInnerObject.getString(EndPoints.TAG_FONT_COLOR));
                Log.d(TAG, "FONT SIZE WOULD BE              " + jsonInnerObject.getInt(EndPoints.TAG_FONT_SIZE));
                Log.d(TAG, "OTHER FONT STYLE WOULD BE       " + jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_STYLE));
                Log.d(TAG, "OTHER FONT COLOR WOULD BE       " + jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_COLOR));
                Log.d(TAG, "OTHER FONT SIZE WOULD BE        " + jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_SIZE));
                Log.d(TAG, "OTHER FONT MAX LENGTH WOULD BE  " + jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_MAX_LENGTH));

                if(EndPoints.TAG_OTHER_FONT_SIZE.matches(""))
                {
                    EndPoints.TAG_OTHER_FONT_SIZE="0";
                }
                if(EndPoints.TAG_OTHER_FONT_MAX_LENGTH.matches(""))
                {
                    EndPoints.TAG_OTHER_FONT_MAX_LENGTH="0";
                }

                SubOptionOneInstance cardInstance = new SubOptionOneInstance(
                        jsonInnerObject.getInt(EndPoints.TAG_ID),
                        jsonInnerObject.getString(EndPoints.TAG_CATEGORY),
                        jsonInnerObject.getBoolean(EndPoints.TAG_ISFRAME),
                        jsonInnerObject.getString(EndPoints.TAG_ORIGINAL_IMAGE_URL),
                        jsonInnerObject.getString(EndPoints.TAG_SAMPLE_IMAGE_URL),
                        jsonInnerObject.getString(EndPoints.TAG_FONT_STYLE),
                        jsonInnerObject.getString(EndPoints.TAG_FONT_COLOR),
                        jsonInnerObject.getInt(EndPoints.TAG_FONT_SIZE),
                        jsonInnerObject.getInt(EndPoints.TAG_FONT_MAX_LENGTH),
                        jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_STYLE),
                        jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_COLOR),
                        jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_SIZE),
                        jsonInnerObject.getString(EndPoints.TAG_OTHER_FONT_MAX_LENGTH));
                subOptionOneInstanceList.add(cardInstance);

            }
//            subOptionOneAdapter.notifyDataSetChanged();
            if (srl_first_fragment.isRefreshing()){
                srl_first_fragment.setRefreshing(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

SubOptionOneAdapter.java

package com.cards.adapter.greetoptions;

public class SubOptionOneAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Object> greetingInstanceList;
    Activity activity;
    private String TAG = getClass().getName();
    private static final int MENU_ITEM_VIEW_TYPE = 0;
    private static final int AD_VIEW = 1;

    public SubOptionOneAdapter() {

    }

    public SubOptionOneAdapter(Activity activity, List<Object> greetingInstanceList) {
        this.greetingInstanceList = greetingInstanceList;
        this.activity = activity;
    }

    public class MenuItemViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView tvCount;
        ProgressBar progressBar;

        public MenuItemViewHolder(View itemView) {
            super(itemView);

            imageView = (ImageView) itemView.findViewById(R.id.ivLatestCardImage);
            tvCount = (TextView) itemView.findViewById(R.id.tvLatestCardTitle);
            progressBar = (ProgressBar) itemView.findViewById(R.id.pbBeforeImage);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder{

        public NativeExpressAdViewHolder(View itemView) {
            super(itemView);
        }
    }

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

    @Override
    public int getItemViewType(int position) {
        return (position % FirstFragment.ITEMS_PER_AD == 0) ? AD_VIEW : MENU_ITEM_VIEW_TYPE;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        switch (viewType)
        {
            case MENU_ITEM_VIEW_TYPE:
               View  view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.latest_list_row,viewGroup,false);
                return new MenuItemViewHolder(view);
            case AD_VIEW:
                // fall through
            default:
                View nativeExpressLayoutView = LayoutInflater.from(
                        viewGroup.getContext()).inflate(R.layout.native_express_ad_container,
                        viewGroup, false);
                return new NativeExpressAdViewHolder(nativeExpressLayoutView);
        }
    }


    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);

        switch (viewType) {
            case MENU_ITEM_VIEW_TYPE:
                final MenuItemViewHolder menuItemViewHolder = (MenuItemViewHolder)holder;
                final SubOptionOneInstance subOptionOneInstance = (SubOptionOneInstance) greetingInstanceList.get(position);
                EndPoints.CUSTOM_ID = "" + subOptionOneInstance.getId();

                Picasso.with(activity)
                        .load(subOptionOneInstance.getSample_image_url())
                        .error(R.drawable.ic_cancel_red)
                        .networkPolicy(NetworkPolicy.OFFLINE)
                        .into(menuItemViewHolder.imageView, new Callback() {
                            @Override
                            public void onSuccess() {
                                if (menuItemViewHolder.progressBar.getVisibility() == View.VISIBLE) {
                                    menuItemViewHolder.progressBar.setVisibility(View.GONE);
                                }
                            }

                            @Override
                            public void onError() {
                                if (menuItemViewHolder.progressBar.getVisibility() == View.VISIBLE) {
                                    menuItemViewHolder.progressBar.setVisibility(View.GONE);
                                }
                                Picasso.with(activity)
                                        .load(subOptionOneInstance.getSample_image_url())
                                        .error(R.drawable.ic_cancel_red)
                                        .into(menuItemViewHolder.imageView, new Callback() {
                                            @Override
                                            public void onSuccess() {

                                            }

                                            @Override
                                            public void onError() {
                                                Log.d(TAG, "PICASSO COULD NOT FETCH IMAGE");
                                            }
                                        });
                            }
                        });

                menuItemViewHolder.tvCount.setText(Integer.toString(subOptionOneInstance.getId()));
                menuItemViewHolder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SubOptionOneInstance instance = (SubOptionOneInstance) greetingInstanceList.get(position);
                        Intent intent = new Intent(activity, CardMaker.class);
                        activity.startActivity(intent);
                        intent.putExtra("id", "" + instance.getId());
                        EndPoints.CUSTOM_ID = "" + instance.getId();
                        EndPoints.CUSTOM_CATEGORY = "" + instance.getCategory();
                        Log.d(TAG, "ID TO BE SEND: " + instance.getId());
                        activity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    }
                });

                break;
            case AD_VIEW:
                    // fall through
                default:
                    NativeExpressAdViewHolder nativeExpressAdViewHolder = (NativeExpressAdViewHolder)holder;
                    NativeExpressAdView nativeExpressAdView = (NativeExpressAdView) greetingInstanceList.get(position);
                    ViewGroup adCardView = (ViewGroup) nativeExpressAdViewHolder.itemView;

                    if(adCardView.getChildCount() >= 0)
                    {
                        adCardView.removeAllViews();
                    }
                    if (nativeExpressAdView.getParent() != null) {
                        ((ViewGroup) nativeExpressAdView.getParent()).removeView(nativeExpressAdView);
                    }

                    // Add the Native Express ad to the native express ad View.
                    adCardView.addView(nativeExpressAdView);
        }
    }
}

Any help would be appreciated!

Pankaj Lilan
  • 3,638
  • 1
  • 27
  • 44
  • 1
    Hi, did you find the answer? i have same issue – Pavel Poley Aug 23 '17 at 09:21
  • I've been trying this out for days now, even following other posts on how to have RecyclerViews with different view types, nothing works so far. I can't even get these views working that hundreds of others say worked for them: https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type – Mr.Drew Nov 02 '18 at 16:04

0 Answers0