Ниже приведены мои фрагменты кода.
1) CustomAdapter
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// A menu item view type.
private static final int MENU_ITEM_VIEW_TYPE = 0;
// The unified native ad view type.
private static final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
ListActivity listActivity;
List<Object> mModelList;
public CustomAdapter(ListActivity listActivity, List<Object> modelList) {
this.listActivity = listActivity;
this.mModelList = modelList;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.ad_unified,
parent, false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
// Fall through.
default:
//inflate layout
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.model_layout, parent, false);
MenuItemViewHolder holder = new MenuItemViewHolder(itemView);
//Handle item clicks here
holder.setOnClickListener(new MenuItemViewHolder.ClickListener() {
@Override
public void onItemClick(View view, int position) {
Model modelList = (Model) mModelList.get(position);
//This is called when user clicks item
String id = modelList.getId();
String title = modelList.getTitle();
String description = modelList.getDescription();
Long time = modelList.getTime();
//intent to start activity
Intent intent = new Intent(listActivity, PostDetails.class);
//put data in intent
intent.putExtra("pId", id);
intent.putExtra("pTitle", title);
intent.putExtra("pDescription", description);
intent.putExtra("pTime", time);
//start activity
listActivity.startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
}
});
return holder;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd nativeAd = (UnifiedNativeAd) mModelList.get(position);
populateNativeAdView(nativeAd, ((UnifiedNativeAdViewHolder) holder).getAdView());
break;
default:
// fall through
case MENU_ITEM_VIEW_TYPE:
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
Model modelList = (Model) mModelList.get(position);
//bind views / set data
menuItemHolder.mTitleTv.setText(modelList.getTitle());
menuItemHolder.mDescriptionTv.setText(modelList.getDescription());
menuItemHolder.setTime(modelList.getTime());
}
}
@Override
public int getItemCount() {
return mModelList.size();
}
@Override
public int getItemViewType(int position) {
Object recyclerViewItem = mModelList.get(position);
if (recyclerViewItem instanceof UnifiedNativeAd) {
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}
return MENU_ITEM_VIEW_TYPE;
}
private void populateNativeAdView(UnifiedNativeAd nativeAd,
UnifiedNativeAdView adView) {
// Some assets are guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
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);
}
}
2) MenuItemViewHolder class
public class MenuItemViewHolder extends RecyclerView.ViewHolder {
TextView mTitleTv, mDescriptionTv, mPostTimeTv;
View mView;
public MenuItemViewHolder(@NonNull View itemView) {
super(itemView);
mView = itemView;
//item click
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mClickListener.onItemClick(v, getAdapterPosition());
}
});
//iten long Click Listener
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mClickListener.onItemLongClick(v, getAdapterPosition());
return true;
}
});
//set time
//initialize views with model_layout.xml
mTitleTv = itemView.findViewById(R.id.rTitleTv);
mDescriptionTv = itemView.findViewById(R.id.rDescriptionTv);
mPostTimeTv = itemView.findViewById(R.id.postTime);
}
public void setTime(Long time) {
TextView txtTime = (TextView) mView.findViewById(R.id.postTime);
//long elapsedDays=0,elapsedWeeks = 0, elapsedHours=0,elapsedMin=0;
long elapsedTime;
long currentTime = System.currentTimeMillis();
int elapsed = (int) ((currentTime - time) / 1000);
if (elapsed < 60) {
if (elapsed < 2) {
txtTime.setText("Just Now");
} else {
txtTime.setText(elapsed + " sec ago");
}
} else if (elapsed > 604799) {
elapsedTime = elapsed / 604800;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " week ago");
} else {
txtTime.setText(elapsedTime + " weeks ago");
}
} else if (elapsed > 86399) {
elapsedTime = elapsed / 86400;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " day ago");
} else {
txtTime.setText(elapsedTime + " days ago");
}
} else if (elapsed > 3599) {
elapsedTime = elapsed / 3600;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " hour ago");
} else {
txtTime.setText(elapsedTime + " hours ago");
}
} else if (elapsed > 59) {
elapsedTime = elapsed / 60;
txtTime.setText(elapsedTime + " min ago");
}
}
private MenuItemViewHolder.ClickListener mClickListener;
//Interface for click listener
public interface ClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public void setOnClickListener (MenuItemViewHolder.ClickListener clickListener) {
mClickListener = clickListener;
}
}
3) ListActivity
public class ListActivity extends AppCompatActivity {
List<Object> modelList = new ArrayList<>();
RecyclerView mRecyclerView;
//private AdView adView;
// The number of native ads to load and display.
public static final int NUMBER_OF_ADS = 5;
// The AdLoader used to load ads.
private AdLoader adLoader;
// List of native ads that have been successfully loaded.
private List<UnifiedNativeAd> mNativeAds = new ArrayList<>();
//layout manager for recyclerview
RecyclerView.LayoutManager layoutManager;
FloatingActionButton mAddBtn;
//firestore instance
FirebaseFirestore db;
CustomAdapter adapter;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
MobileAds.initialize(this, String.valueOf(R.string.admob_app_id));
//actionbar and its title
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("List Data");
//init firestore
db = FirebaseFirestore.getInstance();
//initialize views
mRecyclerView = findViewById(R.id.recycler_view);
mAddBtn = findViewById(R.id.addBtn);
//set Recycler views properties
mRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
//init progree dialog
pd = new ProgressDialog(this);
//show data in recyclerView
showData();
loadNativeAds();
//Handle Floating action button to open main activity
mAddBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
});
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this, getString(R.string.native_advanced_ad));
adLoader = builder.forUnifiedNativeAd(
new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
@Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// A native ad loaded successfully, check if the ad loader has finished loading
// and if so, insert the ads into the list.
mNativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsInMenuItems();
}
}
}).withAdListener(
new AdListener() {
@Override
public void onAdFailedToLoad(int errorCode) {
// A native ad failed to load, check if the ad loader has finished loading
// and if so, insert the ads into the list.
Log.e("MainActivity", "The previous native ad failed to load. Attempting to"
+ " load another.");
if (!adLoader.isLoading()) {
insertAdsInMenuItems();
//showData();
}
}
}).build();
// Load the Native Express ad.
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS);
}
private void insertAdsInMenuItems() {
if (mNativeAds.size() <= 0) {
return;
}
int offset = (modelList.size() / mNativeAds.size()) + 1;
int index = 3;
for (UnifiedNativeAd ad: mNativeAds) {
modelList.add(index, ad);
index = index + offset;
}
}
private void showData() {
//set tittle of progress dialog
pd.setTitle("Loading Data.......");
//show progress dialog
pd.show();
db.collection("Documents")
.orderBy("date", Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
modelList.clear();
//called when data is retrieved
pd.dismiss();
//Show Data
for (DocumentSnapshot doc : task.getResult()) {
Model model = new Model(doc.getString("id"),
doc.getString("title"),
doc.getString("description"),
doc.getLong("time")
);
modelList.add(model);
//insertAdsInMenuItems();
}
//adapter
adapter = new CustomAdapter(ListActivity.this, modelList);
//set adapter to recyclerview
mRecyclerView.setAdapter(adapter);
//mRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//called when there is any error while retrieving
pd.dismiss();
Toast.makeText(ListActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Моя первая проблема заключается в том, что нативная реклама не загружается, пока я не прокручиваю список Список загружается, но реклама не загружается, пока я не прокручиваю вручную и когда я нажимаю на элементы перед прокруткой, происходит сбой моего приложения.
Собственное объявление должно появляться после каждых трех элементов, поэтому, когда я нажимаю на любой элемент ниже трех элементов, происходит сбой приложения с приведенным ниже логотипом.
2019-09-24 14:24: 54.373 27287-27287 / com.pesadevs.firebasefirestore E / AndroidRuntime: ИСКЛЮЧИТЕЛЬНОЕ ИСКЛЮЧЕНИЕ: основной Процесс: com.pesadevs.firebasefirestore, PID: 27287 java.lang.ClassCastException: com.google.android.gms.internal.ads.zzadl не можетбыть приведенным к com.pesadevs.firebasefirestore.Model в com.pesadevs.firebasefirestore.CustomAdapter $ 1.onItemClick (CustomAdapter.java:59) в com.pesadevs.firebasefirestore.MenuItemViewHolder $ 1.onClick (MenuItemViewHolder.java:21) на android.view.View.performClick (View.java:6608) на android.view.View.performClickInternal (View.java:6585) на android.view.View.access $ 3100 (View.java:782) на android.view.View $ PerformClick.run (View.java:25945) на android.os.Handler.handleCallback (Handler.java:874) на android.os.Handler.dispatchMessage (Handler.java:100) наandroid.os.Looper.loop (Looper.java:198) в android.app.ActivityThread.main (ActivityThread.java:6729) в java.lang.reflect.Method.invoke (родной метод) в com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit.java:493) на com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
Примечание: если прокручивается и загружается рекламавсе работает отлично, как видно на моем изображении ниже. Когда реклама загружается, приложение работает как положено.
Я не знаю, что делаю не так, любая помощь будет оценена, спасибо.