Java NullpointerException In Facebook audience native ads, Recyclerview - android

I want to display native ads in predetermined position within my RecyclerView, I have setup the code for showing the ads template but once I integrated the code for showing Facebook Audience native ads the app clashes, I do not know what to after this, is there any one with a solution?
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
return new ViewHolderBoxOffice(layoutInflater.from(parent.getContext()).inflate(R.layout.custom_movie_box_office, parent, false));
case 2:
return new NativeAdViewHolder(layoutInflater.from(parent.getContext()).inflate(R.layout.custom_ads_facebook, parent, false));
}
/*View view=null;
if(viewType==10){
adView= (LinearLayout) layoutInflater.inflate(R.layout.custom_ads_facebook, nativeAdContainer, false);
nativeAdContainer.addView(adView);
} else {
view = layoutInflater.inflate(R.layout.custom_movie_box_office, parent, false);
}
ViewHolderBoxOffice viewHolder = new ViewHolderBoxOffice(view);
return viewHolder;*/
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolderBoxOffice v_holder = (ViewHolderBoxOffice) holder;
Movie currentMovie = mlistMovies.get(position);
v_holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
v_holder.movieReleaseDate.setText(formmattedDate);
} else {
v_holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore = currentMovie.getAudienceScore();
if (audienceScore == -1) {
v_holder.movieAudienceScore.setRating(0.0F);
v_holder.movieAudienceScore.setAlpha(0.5F);
} else {
v_holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
v_holder.movieAudienceScore.setAlpha(1.0F);
}
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, v_holder);
case 2:
NativeAdViewHolder mHolder=(NativeAdViewHolder)holder;
// Setting the Text.
nativeAd.unregisterView();
mHolder.nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
mHolder.nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
mHolder.nativeAdTitle.setText(nativeAd.getAdTitle());
mHolder.nativeAdBody.setText(nativeAd.getAdBody());
// Downloading and setting the ad icon.
NativeAd.Image adIcon = nativeAd.getAdIcon();
NativeAd.downloadAndDisplayImage(adIcon, mHolder.nativeAdIcon);
// Download and setting the cover image.
NativeAd.Image adCoverImage = nativeAd.getAdCoverImage();
mHolder.nativeAdMedia.setNativeAd(nativeAd);
// Add adChoices icon
if (adChoicesView == null)
if(! (adView.getChildAt(0) instanceof AdChoicesView)){
adChoicesView = new AdChoicesView(layoutInflater.getContext(), nativeAd, true);
adView.addView(adChoicesView, 0);
}
nativeAd.registerViewForInteraction(adView);
default:
break;
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}
/* #Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
if (position == 10) {
} else {
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}*/
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return mlistMovies.size();
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
View adView = NativeAdView.render(layoutInflater.getContext(), nativeAd, NativeAdView.Type.HEIGHT_100);
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public int getItemViewType(int position) {
int viewType = 0;
if (position % 10 == 0) viewType = 2;
return viewType;
}
#Override
public void onAdsLoaded() {
}
#Override
public void onAdError(AdError adError) {
}
Here is the error
01-30 20:36:10.721 21295-21295/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 21295
java.lang.NullPointerException
at comeagain.materialdesign.adapters.AdapterBoxOffice.onBindViewHolder(AdapterBoxOffice.java:165)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5217)
I am getting error in the line
if(! (adView.getChildAt(0) instanceof AdChoicesView)){
Changed to this but still getting NullPointerException
if(! (mHolder.adview.getChildAt(0) instanceof AdChoicesView)){
AdChoicesView adChoicesView = new AdChoicesView(layoutInflater.getContext(), nativeAd, true);
mHolder.adview.addView(adChoicesView, 0);
}
nativeAd.registerViewForInteraction(mHolder.adview);
default:
break;
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}
/* #Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
if (position == 10) {
} else {
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}*/
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return mlistMovies.size();
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
}
#Override
public void onAdClicked(Ad ad) {
L.m("Ads is loaded, Jeez man that is good");
System.out.println("Loaded in fragment");
nativeAd = manager.nextNativeAd();
nativeAd.setAdListener(this);
}
#Override
public int getItemViewType(int position) {
int viewType = 0;
if (position % 10 == 0) viewType = 2;
return viewType;
}
#Override
public void onAdsLoaded() {
L.m("Ads is loaded, Jeez man that is good");
System.out.println("Loaded in fragment");
nativeAd = manager.nextNativeAd();
nativeAd.setAdListener(this);
}
#Override
public void onAdError(AdError adError) {
}
class NativeAdViewHolder extends RecyclerView.ViewHolder {
private ImageView nativeAdIcon;
private TextView nativeAdTitle;
private TextView nativeAdBody;
private MediaView nativeAdMedia;
private TextView nativeAdSocialContext;
private Button nativeAdCallToAction;
private LinearLayout adview;
public NativeAdViewHolder(View itemView) {
super(itemView);
// Create native UI using the ad metadata.
nativeAdIcon = (ImageView) itemView.findViewById(R.id.native_ad_icon);
nativeAdTitle = (TextView) itemView.findViewById(R.id.native_ad_title);
nativeAdBody = (TextView) itemView.findViewById(R.id.native_ad_body);
nativeAdMedia = (MediaView) itemView.findViewById(R.id.native_ad_media);
nativeAdSocialContext = (TextView) itemView.findViewById(R.id.native_ad_social_context);
nativeAdCallToAction = (Button) itemView.findViewById(R.id.native_ad_call_to_action);
adview=(LinearLayout) itemView.findViewById(R.id.ads_unit);
}
}
Here is the error
01-30 23:13:06.031 14318-14318/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 14318
java.lang.NullPointerException
at com.facebook.ads.AdChoicesView.a(Unknown Source)
at com.facebook.ads.AdChoicesView.<init>(Unknown Source)
at comeagain.materialdesign.adapters.AdapterBoxOffice.onBindViewHolder(AdapterBoxOffice.java:171)
Error occurs at this point
AdChoicesView adChoicesView = new AdChoicesView(layoutInflater.getContext(), nativeAd, true);

adView is null. In your code there was 1 place where you assigned something to adView but that is commented out, and in another place in onAdLoaded() you assign it to a local variable.

Related

Switch statement behavior at recyclerView when paginate

**I'm working on a market app and at the orders history activity I have to check for order status so at my adapter I make a switch statement to handle it and it works very well
but when I scroll down and the second page called and adapter list update all status changes **
here's my adapter
public class OrdersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
Context context;
List<Orders> ordersList = new ArrayList<>();
private boolean isLoaderVisible = false;
public int selectedPosition;
IClickRecyclerAdapter clickListener;
public OrdersAdapter(Context context, List<Orders> ordersList) {
this.context = context;
if (ordersList != null)
this.ordersList = new ArrayList<>(ordersList);
selectedPosition = -1;
}
public void setClickListener(IClickRecyclerAdapter clickListener) {
this.clickListener = clickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_loading, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
ItemOrderModefiedBinding binding = ItemOrderModefiedBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
viewHolder = new MainViewHolder(binding);
return viewHolder;
}
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Orders orders = ordersList.get(position);
switch (getItemViewType(position)) {
case ITEM:
OrdersAdapter.MainViewHolder mainViewHolder = (OrdersAdapter.MainViewHolder) holder;
if (orders.getStatus() != null) {
mainViewHolder.binding.orderId.setText(orders.getId().toString());
String givenDateString = orders.getCreatedAt();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date mDate = sdf.parse(givenDateString);
long timeInMilliseconds = mDate.getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(timeInMilliseconds, now, DateUtils.MINUTE_IN_MILLIS);
mainViewHolder.binding.date.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
}
switch (orders.getStatus()) {
case "request":
mainViewHolder.binding.line1.setBackgroundColor(context.getColor(R.color.grayModefied));
mainViewHolder.binding.line2.setBackgroundColor(context.getColor(R.color.grayModefied));
mainViewHolder.binding.line3.setBackgroundColor(context.getColor(R.color.grayModefied));
mainViewHolder.binding.requestedText.setVisibility(View.VISIBLE);
mainViewHolder.binding.step1Circle.setBackground(context.getDrawable(R.drawable.purple_circle));
mainViewHolder.binding.step2Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
mainViewHolder.binding.step3Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
mainViewHolder.binding.step4Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
break;
case "approve":
mainViewHolder.binding.line1.setProgress(100,true);
mainViewHolder.binding.line1.setBackgroundColor(context.getColor(R.color.greencolor));
mainViewHolder.binding.line2.setBackgroundColor(context.getColor(R.color.grayModefied));
mainViewHolder.binding.line3.setBackgroundColor(context.getColor(R.color.grayModefied));
mainViewHolder.binding.step1Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.step2Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.step3Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
mainViewHolder.binding.step4Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
mainViewHolder.binding.approvedText.setVisibility(View.VISIBLE);
break;
case "shipping":
mainViewHolder.binding.line1.setProgress(100,true);
mainViewHolder.binding.line1.setIndicatorColor(context.getColor(R.color.orange));
mainViewHolder.binding.line1.postOnAnimationDelayed(() -> {
mainViewHolder.binding.line2.setProgress(100,true);
mainViewHolder.binding.line2.setIndicatorColor(context.getColor(R.color.orange));
},900);
mainViewHolder.binding.step1Circle.setBackground(context.getDrawable(R.drawable.orange_circle));
mainViewHolder.binding.step2Circle.setBackground(context.getDrawable(R.drawable.orange_circle));
mainViewHolder.binding.step3Circle.setBackground(context.getDrawable(R.drawable.orange_circle));
mainViewHolder.binding.step4Circle.setBackground(context.getDrawable(R.drawable.gray_circle));
mainViewHolder.binding.shippingText.setVisibility(View.VISIBLE);
break;
case "deliver":
mainViewHolder.binding.line1.setProgress(100,true);
mainViewHolder.binding.line1.setIndicatorColor(context.getColor(R.color.greencolor));
mainViewHolder.binding.line1.postOnAnimationDelayed(() -> {
mainViewHolder.binding.line2.setProgress(100,true);
mainViewHolder.binding.line2.setIndicatorColor(context.getColor(R.color.greencolor));
},900);
mainViewHolder.binding.line2.postOnAnimationDelayed(() -> {
mainViewHolder.binding.line3.setProgress(100,true);
mainViewHolder.binding.line3.setIndicatorColor(context.getColor(R.color.greencolor));
},1800);
mainViewHolder.binding.step1Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.step2Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.step3Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.step4Circle.setBackground(context.getDrawable(R.drawable.green_circle));
mainViewHolder.binding.deliveredText.setVisibility(View.VISIBLE);
break;
case "cancel":
mainViewHolder.binding.line1.setProgress(100,true);
mainViewHolder.binding.line1.setIndicatorColor(context.getColor(R.color.redcolor));
mainViewHolder.binding.line1.postOnAnimationDelayed(() -> {
mainViewHolder.binding.line2.setProgress(100,true);
mainViewHolder.binding.line2.setIndicatorColor(context.getColor(R.color.redcolor));
},900);
mainViewHolder.binding.line2.postOnAnimationDelayed(() -> {
mainViewHolder.binding.line3.setProgress(100,true);
mainViewHolder.binding.line3.setIndicatorColor(context.getColor(R.color.redcolor));
},1800);
mainViewHolder.binding.step1Circle.setBackground(context.getDrawable(R.drawable.red_circle));
mainViewHolder.binding.step2Circle.setBackground(context.getDrawable(R.drawable.red_circle));
mainViewHolder.binding.step3Circle.setBackground(context.getDrawable(R.drawable.red_circle));
mainViewHolder.binding.step4Circle.setBackground(context.getDrawable(R.drawable.red_circle));
mainViewHolder.binding.deliveredText.setVisibility(View.VISIBLE);
mainViewHolder.binding.deliveredText.setText(R.string.cancel);
break;
}
}
if (clickListener != null) {
holder.itemView.setOnClickListener(view -> {
if (selectedPosition != position) {
if (clickListener != null) {
clickListener.onClickAdapter(position);
}
}
});
}
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return ordersList != null ? ordersList.size() : 0;
}
protected class MainViewHolder extends RecyclerView.ViewHolder {
ItemOrderModefiedBinding binding;
public MainViewHolder(#NonNull ItemOrderModefiedBinding itemView) {
super(itemView.getRoot());
binding = itemView;
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
public Orders getOrders(int position) {
return ordersList.get(position);
}
public void addItems(List<Orders> orders) {
this.ordersList.addAll(orders);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return (position == ordersList.size() - 1 && isLoaderVisible)? LOADING : ITEM;
}
//-----------------------------
public void add(Orders orders) {
ordersList.add(orders);
notifyItemInserted(ordersList.size() - 1);
}
public void addAll(List<Orders> mcList) {
for (Orders mc: mcList) {
add(mc);
}
}
public void remove(Orders orders) {
int position = ordersList.indexOf(orders);
if (position > -1) {
ordersList.remove(position);
notifyItemRemoved(position);
}
}
public void clear() {
isLoaderVisible = false;
ordersList.clear();
while (getItemCount() > 0) {
remove(getItem(0));
notifyDataSetChanged();
}
notifyDataSetChanged();
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoaderVisible = true;
add(new Orders());
}
public void removeLoadingFooter() {
isLoaderVisible = false;
int position = ordersList.size() - 1;
Orders item = getItem(position);
if (item != null) {
ordersList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,ordersList.size());
}
}
public Orders getItem(int position) {
return ordersList.get(position);
}
}
and this is my fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = FragmentAllOrdersBinding.inflate(inflater, container, false);
View view = binding.getRoot();
binding.ordersRecyclerView.setVisibility(View.GONE);
binding.progressLoadingData.setVisibility(View.VISIBLE);
ordersViewModel = new ViewModelProvider(this).get(OrdersViewModel.class);
adapter = new OrdersAdapter(context, null);
linearLayoutManager = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
binding.ordersRecyclerView.addOnScrollListener(new PaginationListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
if (currentPage <= TOTAL_PAGES) {
adapter.addLoadingFooter();
Log.d("TTTT", "loadMoreItems: " + currentPage + " " + TOTAL_PAGES);
new Handler().postDelayed(() -> loadNextPage(), 500);
} else {
isLastPage = true;
}
}
#Override
protected int getTotalPages() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
new Handler().postDelayed(this::loadFirsPage, 500);
binding.ordersRecyclerView.setLayoutManager(linearLayoutManager);
binding.ordersRecyclerView.setAdapter(adapter);
adapter.setClickListener(position -> {
Orders orders = adapter.getItem(position);
Intent intent = new Intent(context, SingleOrderActivity.class);
intent.putExtra(Constant.EXTRA_ORDER_ID, orders.getId());
startActivity(intent);
});
return view;
}
private void loadFirsPage() {
ordersViewModel.getCurrentOrders(currentPage);
ordersViewModel.ordersMutableLiveData.observe(this, orders -> {
binding.progressLoadingData.setVisibility(View.GONE);
if (orders.getStatus().equalsIgnoreCase("success")) {
if(isLoading){
adapter.removeLoadingFooter();
isLoading = false;
}
if (orders.getData().getData().isEmpty()) {
binding.emptyState.setVisibility(View.VISIBLE);
} else {
binding.ordersRecyclerView.setVisibility(View.VISIBLE);
}
adapter.addItems(orders.getData().getData());
TOTAL_PAGES = orders.getData().getLastPage();
if (currentPage != TOTAL_PAGES) {
} else {
if (orders.getData().getLastPage() != 1) {
isLastPage = true;
}
}
}
});
}
private void loadNextPage() {
ordersViewModel.getCurrentOrders(currentPage);
}
and this screen shoot at first call
first image
and this is after scroll to next page
second image

How to efficiently loading native ads on demand with the recyclerview adapter?

What i am doing is, that i have a recyclerView which has it's adapter and from within adapter i am loading the nativeAds. But due to loading the ads within the recyclerView instead of preloading the ads my recyclerView is not scrolling smoothly.
And also i tried to load the native ad on different thread but that also was't helpful.
Any ideas how to load the native ad without sacrificing the performance??
public class GetInspiredAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static int VIEW_TYPE_ADS = 0;
public static int VIEW_TYPE_NOTADS = 1;
// this shows that the ad is to be added after this many items.
public static int ADS_AFTER_HOW_MANY_ITEMS = 3;
private boolean isNetworkAvailable = false;
private Context context;
private ArrayList<Object> list;
private GetInspiredListener listener;
public GetInspiredAdapter(Context context, ArrayList<Object> list, GetInspiredListener listener) {
this.context = context;
this.list = list;
this.listener = listener;
}
private void addNativeToList() {
int i = ADS_AFTER_HOW_MANY_ITEMS;
while (i < list.size()) {
list.add(i, new UnifiedNativeAdView(context));
i += ADS_AFTER_HOW_MANY_ITEMS + 1;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
if (viewType == VIEW_TYPE_ADS) {
View unifiedNativeLayoutView = LayoutInflater.from(context).inflate(R.layout.ad_unified, viewGroup, false);
unifiedNativeLayoutView.setTag(new Integer(GetInspiredAdapter.VIEW_TYPE_ADS));
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
} else {
View itemView = LayoutInflater.from(context).inflate(R.layout.image_item, viewGroup, false);
itemView.setTag(new Integer(GetInspiredAdapter.VIEW_TYPE_NOTADS));
return new GetInspiredViewHolder(itemView);
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
if (viewType == VIEW_TYPE_ADS) {
if (!isNetworkAvailable) {
list.remove(position);
notifyDataSetChanged();
return;
}
AdLoader.Builder builder = new AdLoader.Builder(context, Constants.INSPIRED_MOB)
.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
populateNativeAdView(unifiedNativeAd, (UnifiedNativeAdViewHolder) holder);
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
}
});
builder.build().loadAd(new AdRequest.Builder().build());
} else if (viewType == VIEW_TYPE_NOTADS) {
LoadImage((InspiredObject) list.get(getItemIndex(position)), (GetInspiredViewHolder) holder);
}
}
private void LoadImage(InspiredObject obj, GetInspiredViewHolder viewHolder) {
//Url link to images
String url = "http://aim-itech.com/mandala/image/";
String string = url + obj.low;
Glide.with(context).load(string).override(Constants.SAMPLE_SIZE_MEDIUM).into(viewHolder.imageView);
Log.e("TAG", string);
}
private void populateNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdViewHolder holder) {
if (nativeAd == null) {
holder.getAdView().setVisibility(View.INVISIBLE);
holder.textLoading.setVisibility(View.VISIBLE);
return;
}
holder.textLoading.setVisibility(View.GONE);
UnifiedNativeAdView adView = holder.getAdView();
adView.setVisibility(View.VISIBLE);
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
NativeAd.Image icon = nativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeAd);
}
public int getItemIndex(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = list.get(getItemIndex(position));
if (recyclerViewItem instanceof UnifiedNativeAd) {
return VIEW_TYPE_ADS;
} else if (recyclerViewItem instanceof UnifiedNativeAdView) {
return VIEW_TYPE_ADS;
}
return VIEW_TYPE_NOTADS;
}
public boolean isNetworkAvailable() {
return isNetworkAvailable;
}
public void setNetworkAvailable(boolean networkAvailable) {
isNetworkAvailable = networkAvailable;
if (isNetworkAvailable) {
addNativeToList();
}
}
#Override
public int getItemCount() {
return list.size();
}
public class GetInspiredViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public GetInspiredViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageProf);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InspiredObject inspiredObject = (InspiredObject) list.get(getAdapterPosition());
Intent i = new Intent(context, InspiredActivity.class);
i.putExtra("image", inspiredObject.high);
listener.onClick(i);
}
});
}
}
public class UnifiedNativeAdViewHolder extends RecyclerView.ViewHolder {
private UnifiedNativeAdView adView;
private TextView textLoading;
private CardView adContainer;
public UnifiedNativeAdView getAdView() {
return adView;
}
UnifiedNativeAdViewHolder(View view) {
super(view);
textLoading = view.findViewById(R.id.native_loading_text);
adView = view.findViewById(R.id.native_ad_view);
adContainer = view.findViewById(R.id.ad_unified_conatiner);
// The MediaView will display a video asset if one is present in the ad, and the
// first image asset otherwise.
adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));
// Register the view used for each individual asset.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setBodyView(adView.findViewById(R.id.ad_body));
adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
adView.setIconView(adView.findViewById(R.id.ad_icon));
adView.setPriceView(adView.findViewById(R.id.ad_price));
adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
adView.setStoreView(adView.findViewById(R.id.ad_store));
adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));
}
}
}
surprised there is no answer here.
The approach I would use outside of the recyclerview adapter:
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS_TO_LOAD(Max 5 according to docs);
instead usual adLoader.loadAd
and then
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
}
});
where
private List<UnifiedNativeAd> nativeAds = new ArrayList<>();
which you pass to your recyclerview adapter and mix in your other items.
This will need some memory handling with destroy called before you request another list etc. but the idea is to preload a list of ads instead of loading them while scrolling

Sticky header in RecyclerView with multiple view types not working

I am trying to create a recyclerView with StaggeredGridLayoutManager which contains 4 types of views, namely a header which should stick at top, a card element, a horizontal scrolling ribbon, a loading indicator. All of this works fine if except the sticky header part. I am using header-decor library for the sticky header functionality. Here is my adapter:
public class StickyFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements StickyHeaderAdapter<StickyFeedAdapter.HeaderViewHolder> {
protected final String TAG = getClass().getSimpleName();
private Context context;
private List<FeedItems> feedItems;
private Fragment fragment;
String API;
private String token;
TinyDB tinyDB;
RestAdapter restAdapter;
private static int radius = Utils.dpToPx(28);
private LayoutInflater mInflater;
GApplication application;
MixpanelAPI mixpanel;
private static final int ITEM_TYPE_HEADER = 0, ITEM_TYPE_CARD = 1, ITEM_TYPE_RIBBON = 2, ITEM_TYPE_LOADING = 3;
public StickyFeedAdapter(Context context, List<FeedItems> list, Fragment fragment) {
this.context = context;
this.feedItems = list;
this.fragment = fragment;
mInflater = LayoutInflater.from(context);
application = (GApplication) ((AppCompatActivity) context).getApplication();
API = application.getAPI();
mixpanel = MixpanelAPI.getInstance(context, application.getMixpanelId());
OkHttpClient okHttpClient = new OkHttpClient();
tinyDB = new TinyDB(context);
token = tinyDB.getString(AppConstants.ACCESS_TOKEN);
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", "Token " + token);
}
};
restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API)
.setRequestInterceptor(requestInterceptor)
.build();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LogUtil.i(TAG, "onCreateViewHolder called");
if (viewType == ITEM_TYPE_HEADER) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_row, parent, false);
return new HeaderViewHolder(view);
} else if (viewType == ITEM_TYPE_CARD) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_new_card, parent, false);
return new CardViewHolder(view);
} else if (viewType == ITEM_TYPE_RIBBON) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_row_ribbon, parent, false);
return new RibbonViewHolder(view, context);
} else if (viewType == ITEM_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
return new LoadingViewHolder(view);
} else {
return null;
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
LogUtil.i(TAG, "onBindViewHolder called");
int viewType = getItemViewType(position);
FeedItems currentItem = getItem(position);
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
if (viewType == ITEM_TYPE_HEADER) {
final HeaderItem headerItem = currentItem.getHeaderItem();
layoutParams.setFullSpan(true);
if (headerItem.isFollowing()) {
((HeaderViewHolder) holder).mightLike.setVisibility(View.GONE);
((HeaderViewHolder) holder).followButton.setBackgroundResource(R.drawable.button_background_filled);
((HeaderViewHolder) holder).followText.setTextColor(Color.parseColor("#424447"));
((HeaderViewHolder) holder).followText.setText("FOLLOWING");
} else {
((HeaderViewHolder) holder).mightLike.setVisibility(View.VISIBLE);
((HeaderViewHolder) holder).followButton.setBackgroundResource(R.drawable.button_background);
((HeaderViewHolder) holder).followText.setTextColor(Color.parseColor("#F0F0E9"));
((HeaderViewHolder) holder).followText.setText("FOLLOW");
}
((HeaderViewHolder) holder).followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!headerItem.isFollowing()) {
//follow gallery
headerItem.setFollowing(true);
((HeaderViewHolder) holder).mightLike.setVisibility(View.GONE);
((HeaderViewHolder) holder).followButton.setBackgroundResource(R.drawable.button_background_filled);
((HeaderViewHolder) holder).followText.setTextColor(Color.parseColor("#424447"));
((HeaderViewHolder) holder).followText.setText("FOLLOWING");
follow(headerItem.getGalleryPk());
} else {
//unfollow gallery
headerItem.setFollowing(false);
((HeaderViewHolder) holder).mightLike.setVisibility(View.VISIBLE);
((HeaderViewHolder) holder).followButton.setBackgroundResource(R.drawable.button_background);
((HeaderViewHolder) holder).followText.setTextColor(Color.parseColor("#F0F0E9"));
((HeaderViewHolder) holder).followText.setText("FOLLOW");
unfollow(headerItem.getGalleryPk());
}
}
});
((HeaderViewHolder) holder).shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
((HeaderViewHolder) holder).galleryName.setText(headerItem.getGalleryName());
((HeaderViewHolder) holder).numPhotos.setText(String.format("%s PHOTOS", String.valueOf(headerItem.getNumPhotos())));
((HeaderViewHolder) holder).numFollowers.setText(String.format("%s FOLLOWERS", String.valueOf(headerItem.getNumFollowers())));
} else if (viewType == ITEM_TYPE_CARD) {
final FeedPhoto cardItem = currentItem.getCardItem();
layoutParams.setFullSpan(false);
double aspectRatio = (double) cardItem.getWidth() / cardItem.getHeight();
((CardViewHolder) holder).image.setAspectRatio((float) aspectRatio);
Uri uri = Uri.parse(cardItem.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(((CardViewHolder) holder).image.getController())
.build();
((CardViewHolder) holder).image.setController(controller);
Picasso.with(context)
.load(cardItem.getProfilePic())
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(((CardViewHolder) holder).profilePic);
((CardViewHolder) holder).username.setText(cardItem.getUserName());
((CardViewHolder) holder).timestamp.setText(cardItem.getTime());
if (TextUtils.isEmpty(cardItem.getLocation())) {
((CardViewHolder) holder).locationBox.setVisibility(View.GONE);
} else {
((CardViewHolder) holder).locationBox.setVisibility(View.VISIBLE);
((CardViewHolder) holder).locationText.setText(cardItem.getLocation());
}
if (TextUtils.isEmpty(cardItem.getCaption())) {
((CardViewHolder) holder).captionText.setVisibility(View.GONE);
} else {
((CardViewHolder) holder).captionText.setVisibility(View.VISIBLE);
((CardViewHolder) holder).captionText.setText(cardItem.getCaption());
}
((CardViewHolder) holder).collectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, AddToCollectionActivity.class);
intent.putExtra("photoPk", cardItem.getPk());
intent.putExtra("imageUrl", cardItem.getPhotoUrl());
intent.putExtra("location", cardItem.getLocation());
intent.putExtra("caption", cardItem.getCaption());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_up, R.anim.no_change);
}
});
} else if (viewType == ITEM_TYPE_RIBBON) {
RibbonItem ribbonItem = currentItem.getRibbonItem();
layoutParams.setFullSpan(true);
FeedRibbonAdapter feedRibbonAdapter = new FeedRibbonAdapter(context, fragment, ribbonItem);
((RibbonViewHolder) holder).feedRibbonAdapter = feedRibbonAdapter;
((RibbonViewHolder) holder).ribbonText.setText(ribbonItem.getTitle());
((RibbonViewHolder) holder).recyclerView.setAdapter(feedRibbonAdapter);
} else if (viewType == ITEM_TYPE_LOADING) {
layoutParams.setFullSpan(true);
((LoadingViewHolder) holder).indicator.setVisibility(View.VISIBLE);
}
}
public FeedItems getItem(int position) {
return feedItems.get(position);
}
#Override
public int getItemViewType(int position) {
LogUtil.i(TAG, "getItemViewType called");
FeedItems currentItem = getItem(position);
if (currentItem.getType() == 0) {
return ITEM_TYPE_HEADER;
} else if (currentItem.getType() == 1) {
return ITEM_TYPE_CARD;
} else if (currentItem.getType() == 2) {
return ITEM_TYPE_RIBBON;
} else {
return ITEM_TYPE_LOADING;
}
}
#Override
public int getItemCount() {
return feedItems == null ? 0 : feedItems.size();
}
#Override
public long getHeaderId(int position) {
LogUtil.i(TAG, "getHeaderId called");
if (position == 0) { // don't show header for first item
return StickyHeaderDecoration.NO_HEADER_ID;
} else {
return getHeaderForPosition(position);
}
}
private long getHeaderForPosition(int position) {
for (int i = position; i > 0; i--) {
if (getItem(position) != null) {
if (getItem(position).getType() == 0) {
return (long) i;
}
}
}
return StickyHeaderDecoration.NO_HEADER_ID;
}
#Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
LogUtil.i(TAG, "onCreateHeaderViewHolder called");
View view = mInflater.inflate(R.layout.feed_row, parent, false);
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(final HeaderViewHolder viewholder, int position) {
LogUtil.i(TAG, "onBindHeaderViewHolder called");
FeedItems currentItem = getItem(position);
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) viewholder.itemView.getLayoutParams();
final HeaderItem headerItem = currentItem.getHeaderItem();
layoutParams.setFullSpan(true);
if (headerItem.isFollowing()) {
viewholder.mightLike.setVisibility(View.GONE);
viewholder.followButton.setBackgroundResource(R.drawable.button_background_filled);
viewholder.followText.setTextColor(Color.parseColor("#424447"));
viewholder.followText.setText("FOLLOWING");
} else {
viewholder.mightLike.setVisibility(View.VISIBLE);
viewholder.followButton.setBackgroundResource(R.drawable.button_background);
viewholder.followText.setTextColor(Color.parseColor("#F0F0E9"));
viewholder.followText.setText("FOLLOW");
}
viewholder.followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!headerItem.isFollowing()) {
//follow gallery
headerItem.setFollowing(true);
viewholder.mightLike.setVisibility(View.GONE);
viewholder.followButton.setBackgroundResource(R.drawable.button_background_filled);
viewholder.followText.setTextColor(Color.parseColor("#424447"));
viewholder.followText.setText("FOLLOWING");
follow(headerItem.getGalleryPk());
} else {
//unfollow gallery
headerItem.setFollowing(false);
viewholder.mightLike.setVisibility(View.VISIBLE);
viewholder.followButton.setBackgroundResource(R.drawable.button_background);
viewholder.followText.setTextColor(Color.parseColor("#F0F0E9"));
viewholder.followText.setText("FOLLOW");
unfollow(headerItem.getGalleryPk());
}
}
});
viewholder.shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewholder.galleryName.setText(headerItem.getGalleryName());
viewholder.numPhotos.setText(String.format("%s PHOTOS", String.valueOf(headerItem.getNumPhotos())));
viewholder.numFollowers.setText(String.format("%s FOLLOWERS", String.valueOf(headerItem.getNumFollowers())));
}
public static class HeaderViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.mightLike)
TextView mightLike;
#Bind(R.id.galleryName)
TextView galleryName;
#Bind(R.id.shareButton)
RelativeLayout shareButton;
#Bind(R.id.shareText)
TextView shareText;
#Bind(R.id.followButton)
RelativeLayout followButton;
#Bind(R.id.followText)
TextView followText;
#Bind(R.id.numPhotos)
TextView numPhotos;
#Bind(R.id.numFollowers)
TextView numFollowers;
public HeaderViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.profilePic)
ImageView profilePic;
#Bind(R.id.username)
TextView username;
#Bind(R.id.timestamp)
TextView timestamp;
#Bind(R.id.image)
SimpleDraweeView image;
#Bind(R.id.tagButton)
ImageView tagButton;
#Bind(R.id.reminderButton)
ImageView reminderButton;
#Bind(R.id.collectButton)
RelativeLayout collectButton;
#Bind(R.id.shareButton)
RelativeLayout shareButton;
#Bind(R.id.locationBox)
LinearLayout locationBox;
#Bind(R.id.locationText)
TextView locationText;
#Bind(R.id.captionText)
TextView captionText;
public CardViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public static class RibbonViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.recyclerView)
FlingRecyclerView recyclerView;
#Bind(R.id.ribbonText)
TextView ribbonText;
FeedRibbonAdapter feedRibbonAdapter;
public RibbonViewHolder(View view, Context context) {
super(view);
ButterKnife.bind(this, view);
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
SpacesItemDecoration spacesItemDecoration = new SpacesItemDecoration(Utils.dpToPx(8));
recyclerView.addItemDecoration(spacesItemDecoration);
}
}
public static class LoadingViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.avloadingIndicatorView)
AVLoadingIndicatorView indicator;
public LoadingViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
private static class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int count = state.getItemCount();
if (position == 0) {
outRect.left = space;
outRect.right = space / 2;
} else if (position == count - 1) {
outRect.right = space;
outRect.left = space / 2;
} else {
outRect.left = space / 2;
outRect.right = space / 2;
}
}
}
}
The problem is, the header doesn't stick. It behaves normally. I tried logging the function calls and fount out that getHeaderId() isn't getting called. What could be the reason for that? If anyone has tried this library, does it work with multiple view types? Any help would be highly appreciated.

Add ProgressBar when recyclerView hit scroll

I have to add Pagination in recyclerView. But I am stuck in adding a progressbar when recyclerView scroll.
I have been trying for a day but unfortunately not got a valid solution to add a progress bar at run time while recyclerView scrolling.I have three ViewHolder.
RecyclerView Scroll Listener
rvRewardItems.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = wrapperLinearLayout.getItemCount();
int firstVisibleItem = wrapperLinearLayout.findFirstVisibleItemPosition();
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !isLoadingMore) {
if (!mStopLoadingData) {
try {
isLoadingMore = true;
// Add item for progress ba
new Handler().post(new Runnable() {
#Override
public void run() {
adapter.addProgressView();
}
});
loadReviews(false, false);
}catch (IllegalStateException e){
e.printStackTrace();
}
}
}
}
});
RewardFinalAdapter.class
public class RewardFinalAdapter extends RecyclerView.Adapter<MainViewHolder>
{
private Context context;
private ArrayList<RewardItemBO> rewardArray;
private OnItemClickListener mItemClickListener;
public static final int VIEW_TYPE_PROGRESS = 0;
public static final int VIEW_TYPE_ITEM = 1;
public static final int VIEW_TYPE_HEADER = 2;
public RewardFinalAdapter(Context context, ArrayList<RewardItemBO> mainItems) {
this.context = context;
rewardArray = getFilterRewards(mainItems);
}
public void resetArray(ArrayList<RewardItemBO> latestArray)
{
rewardArray = getFilterRewards(latestArray);
}
public void setArrayItems(ArrayList<RewardItemBO> latestArray) {
rewardArray = latestArray;
}
#Override
public int getItemViewType(int position) {
if(rewardArray.get(position).isHeader())
return VIEW_TYPE_HEADER;
else if(rewardArray.get(position).isShowProgress())
return VIEW_TYPE_PROGRESS;
else
return VIEW_TYPE_ITEM;
}
#Override
public int getItemCount() {
return rewardArray.size();
}
public RewardItemBO getItem(int position) {
return rewardArray.get(position);
}
public void addItems( ArrayList<RewardItemBO> overallItem){
rewardArray = getFilterRewards(overallItem);
// notifyItemInserted(items.size() - 1);
this.notifyDataSetChanged();
}
// Create new views (invoked by the layout manager)
#Override
public MainViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType){
case VIEW_TYPE_HEADER:
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.order_list_header, viewGroup, false);
return new RewardListViewHolderHeader(itemView);
case VIEW_TYPE_ITEM:
View view = LayoutInflater.from(context).inflate(R.layout.item_rewards, viewGroup, false);
return new RewardViewHolder(view);
case VIEW_TYPE_PROGRESS:
Log.v("view_type_progress","I am in VIEW_TYPE_PROGRESS");
View progressView = LayoutInflater.from(context).inflate(R.layout.progress_loader, viewGroup, false);
return new ProgressViewHolder(progressView);
}
return null;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MainViewHolder viewHolder, int position) {
RewardItemBO rewardItemBO= rewardArray.get(position);
if(viewHolder instanceof RewardViewHolder)
{
RewardViewHolder rewardViewHolder=(RewardViewHolder) viewHolder;
rewardViewHolder.tvRewardTitle.setText(rewardArray.get(position).getRewardTitle());
rewardViewHolder.tvRewardDescription.setText(rewardArray.get(position).getRewardMessage());
String formatedDate = DateTimeOp.oneFormatToAnother(rewardArray.get(position).getRewardExpiryDate(), Constants.dateFormat18, Constants.dateFormat6);
rewardViewHolder.tvRewardExpiry.setText("Expires " + formatedDate);
if(rewardArray.get(position).getRewardShowRedeem().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Redeemed");
}
else if(rewardArray.get(position).getRewardExpired().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Expired");
}
else
{
rewardViewHolder.btnOrange.setVisibility(View.VISIBLE);
rewardViewHolder.btnOrange.setText("Get Code");
}
}
else if(viewHolder instanceof RewardListViewHolderHeader)
{
RewardListViewHolderHeader holder = (RewardListViewHolderHeader ) viewHolder;
holder.tvHeader.setText(rewardItemBO.getHeaderTitle());
}
else if(viewHolder instanceof ProgressViewHolder)
{
ProgressViewHolder progressViewHolder = (ProgressViewHolder) viewHolder;
progressViewHolder.progressBar.setIndeterminate(true);
}
}
public void addOnTop(ArrayList<RewardItemBO> topItemList) {
Collections.reverse(topItemList);
rewardArray.addAll(0, topItemList);
notifyItemRangeInserted(0, topItemList.size());
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
#Override
public long getItemId(int position) {
return position;
}
public ArrayList<RewardItemBO> getFilterRewards(ArrayList<RewardItemBO> mainItems){
ArrayList<RewardItemBO> currentRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> pastRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> dummyArray = new ArrayList<>();
for (RewardItemBO rewardItemBO : mainItems) {
try {
//because reward item with progress have everything null in it.
if(rewardItemBO.getRewardExpired()!=null && !rewardItemBO.isShowProgress())
{
int isExpired = Integer.parseInt(rewardItemBO.getRewardExpired());
if(isExpired==1)
pastRewardList.add(rewardItemBO);
else
currentRewardList.add(rewardItemBO);
}
}catch (NumberFormatException e){
e.printStackTrace();
}
}
if(currentRewardList.size()>0){
currentRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Current)));
dummyArray.addAll(currentRewardList);
}
if(pastRewardList.size()>0){
pastRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Past)));
dummyArray.addAll(pastRewardList);
}
return dummyArray;
}
public void addProgressView()
{
rewardArray.add(new RewardItemBO(true));
//notifyItemChanged(rewardArray.size());
notifyDataSetChanged();
}
public void removeProgressView(){
int position = rewardArray.size() -1;
rewardArray.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, rewardArray.size());
}
public static class RewardListViewHolderHeader extends MainViewHolder {
protected TextView tvHeader;
public RewardListViewHolderHeader (View v) {
super(v);
tvHeader = (TextView) v.findViewById(R.id.header_text);
}
}
public class RewardViewHolder extends MainViewHolder implements View.OnClickListener{
public TextView tvRewardTitle;
public TextView tvRewardDescription;
public TextView tvRewardExpiry;
public Button btnOrange,btnGrey;
public RewardViewHolder(View v) {
super(v);
tvRewardTitle = (TextView) itemView.findViewById(R.id.tv_reward_title);
tvRewardDescription = (TextView) itemView.findViewById(R.id.tv_reward_description);
tvRewardExpiry = (TextView) itemView.findViewById(R.id.tv_reward_expiry_date);
btnOrange = (Button) itemView.findViewById(R.id.btn_item_reward_orange);
btnGrey = (Button) itemView.findViewById(R.id.btn_item_reward_grey);
btnOrange.setOnClickListener(this);
btnGrey.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Toast.makeText(context, tvName.getText().toString(), Toast.LENGTH_SHORT).show();
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v,getAdapterPosition());
}
}
}
}

java.lang.ClassCastException In RecycleView, ViewHolder

I have created twoe viewHolders in my RecyclerView class, one for the contents and the other for facebook native ads, My app clash immediately after running it. How do I overcome this?
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
return new ViewHolderBoxOffice(layoutInflater.from(parent.getContext()).inflate(R.layout.custom_movie_box_office, parent, false));
case 2:
return new NativeAdViewHolder(layoutInflater.from(parent.getContext()).inflate(R.layout.custom_ads_facebook, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolderBoxOffice v_holder = (ViewHolderBoxOffice) holder;
Movie currentMovie = mlistMovies.get(position);
v_holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
v_holder.movieReleaseDate.setText(formmattedDate);
} else {
v_holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore = currentMovie.getAudienceScore();
if (audienceScore == -1) {
v_holder.movieAudienceScore.setRating(0.0F);
v_holder.movieAudienceScore.setAlpha(0.5F);
} else {
v_holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
v_holder.movieAudienceScore.setAlpha(1.0F);
}
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, v_holder);
case 2:
NativeAdViewHolder mHolder=(NativeAdViewHolder)holder;
// Setting the Text.
nativeAd.unregisterView();
mHolder.nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
mHolder.nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
mHolder.nativeAdTitle.setText(nativeAd.getAdTitle());
mHolder.nativeAdBody.setText(nativeAd.getAdBody());
// Downloading and setting the ad icon.
NativeAd.Image adIcon = nativeAd.getAdIcon();
NativeAd.downloadAndDisplayImage(adIcon, mHolder.nativeAdIcon);
// Download and setting the cover image.
NativeAd.Image adCoverImage = nativeAd.getAdCoverImage();
mHolder.nativeAdMedia.setNativeAd(nativeAd);
// Add adChoices icon
// if (adChoicesView == null)
if(! (mHolder.adview.getChildAt(0) instanceof AdChoicesView)){
AdChoicesView adChoicesView = new AdChoicesView(layoutInflater.getContext(), nativeAd, true);
mHolder.adview.addView(adChoicesView, 0);
}
nativeAd.registerViewForInteraction( mHolder.adview);
default:
break;
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return mlistMovies.size();
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
}
#Override
public void onAdClicked(Ad ad) {
L.m("Ads is loaded, Jeez man that is good");
System.out.println("Loaded in fragment");
nativeAd = manager.nextNativeAd();
nativeAd.setAdListener(this);
}
#Override
public int getItemViewType(int position) {
int viewType = 0;
if (position % 5 == 1)
viewType = 2;
return viewType;
}
#Override
public void onAdsLoaded() {
L.m("Ads is loaded, Jeez man that is good");
System.out.println("Loaded in fragment");
nativeAd = manager.nextNativeAd();
nativeAd.setAdListener(this);
}
#Override
public void onAdError(AdError adError) {
}
class NativeAdViewHolder extends RecyclerView.ViewHolder {
private ImageView nativeAdIcon;
private TextView nativeAdTitle;
private TextView nativeAdBody;
private MediaView nativeAdMedia;
private TextView nativeAdSocialContext;
private Button nativeAdCallToAction;
private LinearLayout adview;
public NativeAdViewHolder(View itemView) {
super(itemView);
// Create native UI using the ad metadata.
nativeAdIcon = (ImageView) itemView.findViewById(R.id.native_ad_icon);
nativeAdTitle = (TextView) itemView.findViewById(R.id.native_ad_title);
nativeAdBody = (TextView) itemView.findViewById(R.id.native_ad_body);
nativeAdMedia = (MediaView) itemView.findViewById(R.id.native_ad_media);
nativeAdSocialContext = (TextView) itemView.findViewById(R.id.native_ad_social_context);
nativeAdCallToAction = (Button) itemView.findViewById(R.id.native_ad_call_to_action);
adview=(LinearLayout) itemView.findViewById(R.id.ads_unit);
}
}
class ViewHolderBoxOffice extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView movieThumbnail;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieAudienceScore;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
movieThumbnail = (ImageView) itemView.findViewById(R.id.movieThumbnail);
movieTitle = (TextView) itemView.findViewById(R.id.movieTitle);
movieReleaseDate = (TextView) itemView.findViewById(R.id.movieReleaseDate);
movieAudienceScore = (RatingBar) itemView.findViewById(R.id.movieAudienceScore);
}
Here is the error.
01-31 16:30:48.944 9429-9429/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 9429
java.lang.ClassCastException: comeagain.materialdesign.adapters.AdapterBoxOffice$ViewHolderBoxOffice cannot be cast to comeagain.materialdesign.adapters.AdapterBoxOffice$NativeAdViewHolder
at comeagain.materialdesign.adapters.AdapterBoxOffice.onBindViewHolder(AdapterBoxOffice.java:148)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5217)
Error is at line
NativeAdViewHolder mHolder=(NativeAdViewHolder)holder;
I unable to determine what is the problem and how to solve this issue. Kindly help.
Terminate your Switch case with a break.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolderBoxOffice v_holder = (ViewHolderBoxOffice) holder;
Movie currentMovie = mlistMovies.get(position);
v_holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
v_holder.movieReleaseDate.setText(formmattedDate);
} else {
v_holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore = currentMovie.getAudienceScore();
if (audienceScore == -1) {
v_holder.movieAudienceScore.setRating(0.0F);
v_holder.movieAudienceScore.setAlpha(0.5F);
} else {
v_holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
v_holder.movieAudienceScore.setAlpha(1.0F);
}
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, v_holder);
break;
case 2:
NativeAdViewHolder mHolder=(NativeAdViewHolder)holder;
// Setting the Text.
nativeAd.unregisterView();
mHolder.nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
mHolder.nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
mHolder.nativeAdTitle.setText(nativeAd.getAdTitle());
mHolder.nativeAdBody.setText(nativeAd.getAdBody());
// Downloading and setting the ad icon.
NativeAd.Image adIcon = nativeAd.getAdIcon();
NativeAd.downloadAndDisplayImage(adIcon, mHolder.nativeAdIcon);
// Download and setting the cover image.
NativeAd.Image adCoverImage = nativeAd.getAdCoverImage();
mHolder.nativeAdMedia.setNativeAd(nativeAd);
// Add adChoices icon
// if (adChoicesView == null)
if(! (mHolder.adview.getChildAt(0) instanceof AdChoicesView)){
AdChoicesView adChoicesView = new AdChoicesView(layoutInflater.getContext(), nativeAd, true);
mHolder.adview.addView(adChoicesView, 0);
}
nativeAd.registerViewForInteraction( mHolder.adview);
break;
default:
break;
}
if (position > previousPosition) {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
} else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition = position;
}
And next time use a debbuger to find stuff like this.

Categories

Resources