我正在开发一个Android应用程序,它从JSON Url获取数据并将其显示到Recyclerview中。我想在项目之间添加原生广告,因此我按照本教程Git Hub Tutorial将NativeExpressAdView添加到Recyclerview中。 我在onBindViewHolder()
上收到错误我得到的错误是
ava.lang.ClassCastException:com.sctar.moviestime.myRecycler.GetDataAdapter无法强制转换为com.google.android.gms.ads.NativeExpressAdView 在com.sctar.moviestime.myRecycler.MyAdapter.onBindViewHolder(MyAdapter.java:119
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
private List<Object> mRecyclerViewItems;
private static final int MOVIE_ITEM_VIEW_TYPE=0;
private static final int SCROLL_AD_VIEW=1;
public MyAdapter(Context context,List<Object> mRecyclerViewItems)
{
super();
this.mContext=context;
this.mRecyclerViewItems=mRecyclerViewItems;
}
public class MoviesItemViewHolder extends RecyclerView.ViewHolder {
public TextView movieNameTV,movieGenreTV;
public YouTubeThumbnailView videoThumbnail;
public String movie_url="";
public MoviesItemViewHolder(View mView) {
super(mView);
movieNameTV=(TextView)mView.findViewById(R.id.movieNameTV);
movieGenreTV=(TextView)mView.findViewById(R.id.movieGenre);
videoThumbnail=(YouTubeThumbnailView)mView.findViewById(R.id.thumbnailView1);
videoThumbnail.initialize(DeveloperKey.DEV_KEY, new YouTubeThumbnailView.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(movie_url);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
@Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailLoader.release();
}
@Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
});
}
@Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
public class NativeExpressViewHolder extends RecyclerView.ViewHolder
{
public NativeExpressViewHolder(View itemView) {
super(itemView);
}
}
@Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
@Override
public int getItemViewType(int position) {
return (position%HomeFragment.ITEMS_PER_AD==0)?SCROLL_AD_VIEW:MOVIE_ITEM_VIEW_TYPE;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case SCROLL_AD_VIEW:
View scroll_ad_layout=LayoutInflater.from(parent.getContext()).inflate(R.layout.scroll_ad_layout,parent,false);
return new NativeExpressViewHolder(scroll_ad_layout);
case MOVIE_ITEM_VIEW_TYPE:
//Fall through
default:
View movie_item_view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_card, parent, false);
return new MoviesItemViewHolder(movie_item_view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case SCROLL_AD_VIEW:
NativeExpressViewHolder nativeExpressViewHolder = (NativeExpressViewHolder) holder;
NativeExpressAdView nativeExpressAdView= (NativeExpressAdView) mRecyclerViewItems.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressViewHolder.itemView;
adCardView.removeAllViews();
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (nativeExpressAdView.getParent() != null) {
((ViewGroup) nativeExpressAdView.getParent()).removeView(nativeExpressAdView);
}
adCardView.addView(nativeExpressAdView);
break;
case MOVIE_ITEM_VIEW_TYPE:
//Fall Through
default:
MoviesItemViewHolder moviesItemViewHolder = (MoviesItemViewHolder) holder;
GetDataAdapter cardItem = (GetDataAdapter) mRecyclerViewItems.get(position);
moviesItemViewHolder.movieNameTV.setText(cardItem.getName());
moviesItemViewHolder.movieGenreTV.setText(cardItem.getGenre());
moviesItemViewHolder.movie_url = cardItem.getMovie_url();
break;
}
}
}
HomeFragment.java类
public class HomeFragment extends Fragment {
YouTubePlayerSupportFragment youTubePlayerFragment;
RecyclerView recyclerView;
String GET_JSON_DATA_URL="http://sctar.com/moviestime/admin/getMovie.php?page=";
String JSON_NAME="movie_name";
String JSON_GENRE="movie_genre";
String JSON_URL="movie_url";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
TextView movieName,play_movieName;
EqualizerView equalizerView;
ProgressBar progressBar;
private int pageNumber=1;
GetDataAdapter cardItem;
private List<Object> mRecyclerViewItems;
public static final int ITEMS_PER_AD=8;
private static final int NATIVE_EXPRESS_AD_HEIGHT=150;
private static final String AD_UNIT_ID="ca-app-pub-1094536469217749/8160042117";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.home_fragment,container,false);
setRetainInstance(true);
recyclerView=(RecyclerView)view.findViewById(R.id.homeRV);
recyclerView.setHasFixedSize(true);
movieName=(TextView)view.findViewById(R.id.movieNameTV);
play_movieName=(TextView)view.findViewById(R.id.play_movieNameTV);
//Specify a Layout Manager
RecyclerView.LayoutManager linearLayoutManager=new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
mRecyclerViewItems=new ArrayList<>();
progressBar=(ProgressBar)view.findViewById(R.id.progressBar);
equalizerView=(EqualizerView)view.findViewById(R.id.equalizer_view);
//Update RecyclerView Items
//addData();
youTubePlayerFragment=YouTubePlayerSupportFragment.newInstance();
FragmentTransaction fragmentTransaction=getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.youtube_fragment,youTubePlayerFragment).commit();
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, final int position, View v) {
youTubePlayerFragment.initialize(DeveloperKey.DEV_KEY, new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer yPlayer, boolean b) {
if(!b)
{
cardItem=(GetDataAdapter)mRecyclerViewItems.get(position);
String movie_url=cardItem.getMovie_url();
yPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
yPlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
//yPlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
yPlayer.loadVideo(movie_url);
yPlayer.play();
equalizerView.animateBars();
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
youTubePlayerFragment.onDestroy();
}
});
//Get Data from the Server
addData();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(isLastItemDisplaying(recyclerView)) {
addData();
}
}
});
}
else {
recyclerView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View view, int i, int i1, int i2, int i3) {
if(isLastItemDisplaying(recyclerView))
addData();
}
});
}
// addData();
//Load Native and Banner Ads
addNativeScrollAds();
setupAndLoadNativeAds();
addBannerAds(view);
return view;
}
public void addData()
{
progressBar.setVisibility(View.VISIBLE);
requestQueue=Volley.newRequestQueue(this.getActivity());
requestQueue.add(json_web_call(pageNumber));
pageNumber++;
}
private void addNativeScrollAds(){
Toast.makeText(getActivity(),String.valueOf(mRecyclerViewItems.size()), Toast.LENGTH_SHORT).show();
for(int i=0;i<mRecyclerViewItems.size();i+=ITEMS_PER_AD){
NativeExpressAdView adView=new NativeExpressAdView(this.getActivity());
adView.setAdSize(new AdSize(320,150));
adView.setAdUnitId(AD_UNIT_ID);
adView.loadAd(new AdRequest.Builder().build());
mRecyclerViewItems.add(i,adView);
}
}
public void setupAndLoadNativeAds(){
recyclerView.post(new Runnable() {
@Override
public void run() {
Toast.LENGTH_SHORT).show();
final float scale=getContext().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 <mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
CardView cardView=(CardView)getActivity().findViewById(R.id.scrollAdCard);
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(8);
}
});
}
private void loadNativeExpressAd(final int index){
if(index>=mRecyclerViewItems.size()){
return;
}
Object item=mRecyclerViewItems.get(index);
if(!(item instanceof NativeExpressAdView)){
throw new ClassCastException("Expected Item at Index "+index+" to be a Native Express Adview");
}
final NativeExpressAdView adView=(NativeExpressAdView)item;
adView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
super.onAdLoaded();
loadNativeExpressAd(index+ITEMS_PER_AD);
}
@Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
Log.e("HomeFragment","The Previous native ad failed to load, attempting to load next ad in item list");
loadNativeExpressAd(index+ITEMS_PER_AD);
}
});
adView.loadAd(new AdRequest.Builder().build());
// Toast.makeText(getActivity(),String.valueOf(mRecyclerViewItems.size()), Toast.LENGTH_SHORT).show();
}
public void addBannerAds(View view){
AdView bannerAdView=(AdView)view.findViewById(R.id.bannerAdview1);
AdRequest bannerAdRequest=new AdRequest.Builder().addTestDevice("cph1701-a17bc212").build();
bannerAdView.loadAd(bannerAdRequest);
}
public JsonArrayRequest json_web_call(int pageNumber)
{
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest=new JsonArrayRequest(GET_JSON_DATA_URL+String.valueOf(pageNumber), new Response.Listener<JSONArray>() {
//jsonArrayRequest=new JsonArrayRequest(GET_JSON_DATA_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
json_parse_data(response);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
}
});
return jsonArrayRequest;
//requestQueue=Volley.newRequestQueue(this.getActivity());
//requestQueue.add(jsonArrayRequest);
}
public void json_parse_data(JSONArray array)
{
for(int i=0;i<array.length();i++)
{
try {
JSONObject json=array.getJSONObject(i);
String name=json.getString(JSON_NAME);
String genre=json.getString(JSON_GENRE);
String movie_url=json.getString(JSON_URL);
GetDataAdapter menuItem=new GetDataAdapter(name,genre,movie_url);
//if(i%ITEMS_PER_AD!=0)
mRecyclerViewItems.add(menuItem);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
MyAdapter myAdapter=new MyAdapter(this.getContext(),mRecyclerViewItems);
recyclerView.setAdapter(myAdapter);
}
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if(recyclerView.getAdapter().getItemCount()!=0){
int lastVisibleItem=((LinearLayoutManager)recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if(lastVisibleItem!=RecyclerView.NO_POSITION && lastVisibleItem==recyclerView.getAdapter().getItemCount()-1)
return true;
}
return false;
}
}
GetDataAdapter类
public class GetDataAdapter {
int id;
String name;
String genre;
String movie_url;
public GetDataAdapter(){
//Default Constructor
}
public GetDataAdapter(String name,String genre,String movie_url){
this.name=name;
this.genre=genre;
this.movie_url=movie_url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getMovie_url() {
return movie_url;
}
public void setMovie_url(String movie_url) {
this.movie_url = movie_url;
}
}
答案 0 :(得分:0)
第一个问题应该是=
类addNativeScrollAds
方法中缺少HomeFragment
符号, for 周期。
你应该像这样添加它(阅读内联评论):
for (int i=0; i<=/*i added equals here*/mRecyclerViewItems.size(); i+=ITEMS_PER_AD){
NativeExpressAdView adView = new NativeExpressAdView(this.getActivity());
adView.setAdSize(new AdSize(320,150));
adView.setAdUnitId(AD_UNIT_ID);
adView.loadAd(new AdRequest.Builder().build());
mRecyclerViewItems.add(i,adView);
}
第二个问题应该在setupAndLoadNativeAds
方法中,其中for循环在完全相同的位置缺少=
。
如果这解决了问题,请告诉我