Unable to initialize native ad inside recyclerview in androidX - android

I was trying to implement Admob native ads inside my recyclerView, And i ended with below error & i have also attached my code. i even followed Google Code Lab. Still i ended with multiple error.
How do i add native ad's between <Arraylist>.
FYI: i have minimized code to be readable.
MainActivity:
public class MainActivity extends AppCompatActivity {
public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;
#BindView(R.id.recyclerView) RecyclerView recyclerView;
ArrayList<VideoModel> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
adMob();
arrayListVideos = new ArrayList<>();
mLayoutManager = new GridLayoutManager(this, autoCardWith);
//mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// #Override
//public int getSpanSize(int position) { if (position % MainActivity.ITEMS_PER_AD == 0) { return autoCardWith; } return 1; }
//});
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
recyclerView.setHasFixedSize(true);
shimmerFrameLayout = findViewById(R.id.shimmer_view);
shimmerFrameLayout.setVisibility(View.VISIBLE);
shimmerFrameLayout.startShimmer();
recyclerView.setVisibility(View.INVISIBLE);
askPermission();
displayAllVideos();
loadNativeAds();
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}
private void insertAdsinMenuItem() {
if (nativeAds.size() < 0 ){
return;
}
int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
int index = 0;
for (UnifiedNativeAd ad:nativeAds){
arrayListVideos.add(index,ad);
index = index + offset;
}
}
private void adMob() {
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.main_banner);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
private void askPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,2084);
}
}
private void displayAllVideos() {
Uri uri;
Cursor cursor;
int column_index_data,thum;
String absolutePathThumb;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()){
Log.d("VIDEO", cursor.getString(0));
absolutePathThumb = cursor.getString(column_index_data);
Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
//String cursorThumb = cursor.getString(thum);
String fileName = FilenameUtils.getBaseName(absolutePathThumb);
String extension = FilenameUtils.getExtension(absolutePathThumb);
String duration = getDuration(absolutePathThumb);
VideoModel videoModel = new VideoModel();
videoModel.setDuration(duration);
videoModel.setVideo_uri(thumbUri.toString());
videoModel.setVideo_path(absolutePathThumb);
videoModel.setVideo_name(fileName);
videoModel.setVideo_thumb(cursor.getString(thum));
if (extension!=null){
videoModel.setVideo_extension(extension);
}else {
videoModel.setVideo_extension("mp4");
}
if (duration!=null){
videoModel.setDuration(duration);
}else {
videoModel.setDuration("00:00");
}
arrayListVideos.add(videoModel);
}
videoAdapter = new VideoAdapter(this,arrayListVideos);
shimmerFrameLayout.setVisibility(View.INVISIBLE);
shimmerFrameLayout.stopShimmer();
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(videoAdapter);
//set adapter
}
}
VideoAdapter:
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoAdapterViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
Context context;
ArrayList<VideoModel> arrayListVideo;
ArrayList<VideoModel> arrayListVideoAll;
private Activity mainActivity;
public VideoAdapter(Context context, ArrayList<VideoModel> arrayListVideos){
this.context = context;
this.arrayListVideo = arrayListVideos;
arrayListVideoAll = new ArrayList<>(arrayListVideo);
mainActivity = (Activity) context;
}
#NonNull
#Override
public VideoAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified,viewGroup,false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
default:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos,viewGroup,false);
return new VideoAdapterViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull VideoAdapterViewHolder videoAdapterViewHolder, int i) {
int viewType = getItemViewType(i);
switch (viewType){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd)arrayListVideo.get(i);
populateNativeAdView(unifiedNativeAd,((UnifiedNativeAdViewHolder)videoAdapterViewHolder).getAdView());
break;
case MENU_ITEM_VIEW_TYPE:
Glide.with(context).load(arrayListVideo.get(i).getVideo_thumb()).into(videoAdapterViewHolder.image);
videoAdapterViewHolder.name.setText(arrayListVideo.get(i).getVideo_name() + "." + arrayListVideo.get(i).getVideo_extension());
videoAdapterViewHolder.duration.setText(arrayListVideo.get(i).getDuration());
}
}
#Override
public int getItemCount() {
return arrayListVideo.size();
}
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder{
public ImageView image;
public TextView name,duration;
public ImageView videoOption;
public VideoAdapterViewHolder(#NonNull View itemView) {
super(itemView);
if (!(itemView instanceof AdView)) {
image = (ImageView)itemView.findViewById(R.id.vid_image);
name = (TextView)itemView.findViewById(R.id.vid_name);
duration = (TextView)itemView.findViewById(R.id.vid_duration);
videoOption = (ImageView) itemView.findViewById(R.id.video_option);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
((MainActivity)context).openVideoPlayerActivity(videoModel);
}
});
videoOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
((MainActivity)context).VideoMoreOption(videoModel);
}
});
}
}
}
private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
((TextView)adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
((TextView)adView.getBodyView()).setText(unifiedNativeAd.getBody());
((TextView)adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());
NativeAd.Image icon = unifiedNativeAd.getIcon();
if (icon==null){
adView.getIconView().setVisibility(View.INVISIBLE);
}else {
((ImageView)adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if(unifiedNativeAd.getPrice()==null){
adView.getPriceView().setVisibility(View.INVISIBLE);
}else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView)adView.getPriceView()).setText(unifiedNativeAd.getPrice());
}
if(unifiedNativeAd.getStarRating()==null){
adView.getStarRatingView().setVisibility(View.INVISIBLE);
}else {
adView.getStarRatingView().setVisibility(View.VISIBLE);
((RatingBar)adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
}
if(unifiedNativeAd.getAdvertiser()==null){
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
}else {
adView.getAdvertiserView().setVisibility(View.VISIBLE);
((TextView)adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
}
adView.setNativeAd(unifiedNativeAd);
}
}

public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
Context context;
ArrayList<Object> arrayListVideo;
ArrayList<Object> arrayListVideoAll;
private Activity mainActivity;
public VideoAdapter(Context context, ArrayList<Object> arrayListVideos) {
this.context = context;
this.arrayListVideo = arrayListVideos;
arrayListVideoAll = new ArrayList<>(arrayListVideo);
mainActivity = (Activity) context;
}
#Override
public int getItemViewType(int position) {
if(arrayListVideo.get(position) instanceof VideoModel){
return MENU_ITEM_VIEW_TYPE;
} else{
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified, viewGroup, false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
default:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos, viewGroup, false);
return new VideoAdapterViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
switch (viewHolder.getItemViewType()) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd) arrayListVideo.get(i);
populateNativeAdView(unifiedNativeAd, ((UnifiedNativeAdViewHolder) viewHolder).getAdView());
break;
case MENU_ITEM_VIEW_TYPE:
final VideoAdapterViewHolder videoAdapterViewHolder = (VideoAdapterViewHolder) viewHolder;
final VideoModel item = (VideoModel) arrayListVideo.get(i);
Glide.with(context).load(item.getVideo_thumb()).into(videoAdapterViewHolder.image);
videoAdapterViewHolder.name.setText(item.getVideo_name() +
"." + item.getVideo_extension());
videoAdapterViewHolder.duration.setText(item.getDuration());
}
}
#Override
public int getItemCount() {
return arrayListVideo.size();
}
#Override
public Filter getFilter() {
return null;
}
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView name, duration;
public ImageView videoOption;
public VideoAdapterViewHolder(#NonNull View itemView) {
super(itemView);
if (!(itemView instanceof AdView)) {
image = (ImageView) itemView.findViewById(R.id.vid_image);
name = (TextView) itemView.findViewById(R.id.vid_name);
duration = (TextView) itemView.findViewById(R.id.vid_duration);
videoOption = (ImageView) itemView.findViewById(R.id.video_option);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
((MainActivity) context).openVideoPlayerActivity(videoModel);
}
});
videoOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
((MainActivity) context).VideoMoreOption(videoModel);
}
});
}
}
}
private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
((TextView) adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(unifiedNativeAd.getBody());
((TextView) adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());
NativeAd.Image icon = unifiedNativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (unifiedNativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(unifiedNativeAd.getPrice());
}
if (unifiedNativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
adView.getStarRatingView().setVisibility(View.VISIBLE);
((RatingBar) adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
}
if (unifiedNativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
adView.getAdvertiserView().setVisibility(View.VISIBLE);
((TextView) adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
}
adView.setNativeAd(unifiedNativeAd);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
ArrayList<Object> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
adMob();
arrayListVideos = new ArrayList<>();
mLayoutManager = new GridLayoutManager(this, autoCardWith);
//mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// #Override
//public int getSpanSize(int position) { if (position % MainActivity.ITEMS_PER_AD == 0) { return autoCardWith; } return 1; }
//});
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
recyclerView.setHasFixedSize(true);
shimmerFrameLayout = findViewById(R.id.shimmer_view);
shimmerFrameLayout.setVisibility(View.VISIBLE);
shimmerFrameLayout.startShimmer();
recyclerView.setVisibility(View.INVISIBLE);
askPermission();
displayAllVideos();
loadNativeAds();
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}
private void insertAdsinMenuItem() {
if (nativeAds.size() < 0 ){
return;
}
int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
int index = 0;
for (UnifiedNativeAd ad:nativeAds){
arrayListVideos.add(index,ad);
index = index + offset;
}
}
private void adMob() {
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.main_banner);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
private void askPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,2084);
}
}
private void displayAllVideos() {
Uri uri;
Cursor cursor;
int column_index_data,thum;
String absolutePathThumb;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()){
Log.d("VIDEO", cursor.getString(0));
absolutePathThumb = cursor.getString(column_index_data);
Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
//String cursorThumb = cursor.getString(thum);
String fileName = FilenameUtils.getBaseName(absolutePathThumb);
String extension = FilenameUtils.getExtension(absolutePathThumb);
String duration = getDuration(absolutePathThumb);
VideoModel videoModel = new VideoModel();
videoModel.setDuration(duration);
videoModel.setVideo_uri(thumbUri.toString());
videoModel.setVideo_path(absolutePathThumb);
videoModel.setVideo_name(fileName);
videoModel.setVideo_thumb(cursor.getString(thum));
if (extension!=null){
videoModel.setVideo_extension(extension);
}else {
videoModel.setVideo_extension("mp4");
}
if (duration!=null){
videoModel.setDuration(duration);
}else {
videoModel.setDuration("00:00");
}
arrayListVideos.add(videoModel);
}
videoAdapter = new VideoAdapter(this,arrayListVideos);
shimmerFrameLayout.setVisibility(View.INVISIBLE);
shimmerFrameLayout.stopShimmer();
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(videoAdapter);
//set adapter
}
}

Related

I'm using RecyclerView and I want to randomly display images

I'm making a Wallpaper app using RecyclerView, and I want to know how to do random (shuffle), so I'm looking for a way, but I can't find a good way. Please let me know how to solve it. Thank you in advance.
I share the source I am using. I am not a professional developer, but I am a person who makes apps as a hobby, so I still lack a lot. Sorry and thank you.
MainActivity
public class MainActivity extends AppCompatActivity {
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
RecyclerView recyclerView = findViewById(R.id.rv_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SpacesItemDecoration());
ImageGalleryAdapter adapter = new ImageGalleryAdapter(this, WallPhoto.getWallPhotos());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
class ImageGalleryAdapter extends RecyclerView.Adapter<ImageGalleryAdapter.MyViewHolder> {
private WallPhoto[] mWallPhotos;
private Context mContext;
public ImageGalleryAdapter(Context context, WallPhoto[] WallPhotos) {
mContext = context;
mWallPhotos = WallPhotos;
}
#Override
public ImageGalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View photoView = inflater.inflate(R.layout.item_photo, parent, false);
ImageGalleryAdapter.MyViewHolder viewHolder = new ImageGalleryAdapter.MyViewHolder(photoView);
return viewHolder;
}
#Override
public void onBindViewHolder(ImageGalleryAdapter.MyViewHolder holder, int position) {
WallPhoto WallPhoto = mWallPhotos[position];
ImageView imageView = holder.mPhotoImageView;
Picasso.get()
.load(WallPhoto.getUrl())
.resize(200, 320)
.centerCrop()
.into(imageView);
}
#Override
public int getItemCount() {
return (mWallPhotos.length);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mPhotoImageView;
public MyViewHolder(View itemView) {
super(itemView);
mPhotoImageView = itemView.findViewById(R.id.iv_photo);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
WallPhoto WallPhoto = mWallPhotos[position];
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_TRAVEL_PHOTO, WallPhoto);
startActivity(intent);
}
}
}
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.SET_WALLPAPER,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION)
.check();
}
}
WallPhoto
public class WallPhoto implements Parcelable {
public static final Creator<WallPhoto> CREATOR = new Creator<WallPhoto>() {
#Override
public WallPhoto createFromParcel(Parcel in) {
return new WallPhoto(in);
}
#Override
public WallPhoto[] newArray(int size) {
return new WallPhoto[size];
}
};
private String mUrl;
public WallPhoto(String url) {
mUrl = url;
}
protected WallPhoto(Parcel in) {
mUrl = in.readString();
}
public static WallPhoto[] getWallPhotos() {
return new WallPhoto[]{
new WallPhoto("https://i.pinimg.com/736x/55/42/b4/5542b4fce27fb35f586db30f22aa7a06.jpg"),
new WallPhoto("https://i.pinimg.com/736x/dd/46/07/dd4607dfa77d3954ebd3bc5514d3b160.jpg"),
new WallPhoto("https://i.pinimg.com/736x/b1/a6/d6/b1a6d66f1dc350a6eb07098b031a6a86.jpg"),
new WallPhoto("https://i.pinimg.com/736x/ea/43/16/ea43160566df2e94804dc8494abad75d.jpg"),
new WallPhoto("https://i.pinimg.com/736x/2c/9c/e1/2c9ce1ebebcdd9f94bffa7d3a75ba172.jpg"),
new WallPhoto("https://i.pinimg.com/736x/a7/0a/3d/a70a3d6f310f63df2556233466c0d1a5.jpg"),
new WallPhoto("https://i.pinimg.com/736x/54/b3/20/54b320780750126d3c2c014af78e2642.jpg"),
new WallPhoto("https://i.pinimg.com/736x/3f/cc/ec/3fccec232da73ea7efe334cdfa920085.jpg"),
new WallPhoto("https://i.pinimg.com/736x/3b/c1/9f/3bc19f6a11ce39f1ce534b800001e4e0.jpg"),
new WallPhoto("https://i.pinimg.com/736x/37/a8/6e/37a86eac7b57ad3f768771870aca68ca.jpg"),
};
}
public String getUrl() {
return mUrl;
}
public void setUrl(String url) {
mUrl = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mUrl);
}
}
public void shuffle() {
int mWallPhotoSize = mWallphoto.length();
WallPhoto[] shuffleWallphoto = new WallPhoto[mWallPhotoSize];
boolean[] checkNumber = new boolean[mWallPhotoSize];
for (int i = 0; i < mWallPhotoSize; i++) {
int randomNumber = (int)(Math.random()*mWallPhotoSize);
if (!checkNumber[randomNumber]) {
checkNumber[randomNumber] = true;
shuffleWallphoto[i] = mWallphoto[randomNumber];
} else {
i--;
}
}
mWallphoto = shuffleWallphoto;
}

Add some fragment continuously then RecyclerView scroll lagging

Add some fragment continuously then RecyclerView scroll lagging
I am remove image load library but not any improvement i am face same
problem.
I am also check this link click
add fragment then facing this problem. but replace fragment then not facing this problem
more add fragment then RecyclerView lagging. i think fragment memory issue
add more then three fragment continuously then face this problem
fragment xml
<FrameLayout
android:id="#+id/frameLayout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_main"
android:layout_above="#+id/linearLayout_adView_main" />
call fragment data
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelatedFragment relatedFragment = new RelatedFragment();
Bundle bundle = new Bundle();
bundle.putString("type", "related");
bundle.putString("post_id", statusLists.getId());
bundle.putString("cat_id", statusLists.getCid());
bundle.putString("typeLayout", "Landscape");
relatedFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, relatedFragment, string).addToBackStack(string).commitAllowingStateLoss();
}
});
xml file
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_sub_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp" />
Fragment
public class RelatedFragment extends Fragment {
private Method method;
private OnClick onClick;
private String type, post_id, cat_id, typeLayout;
private ProgressBar progressBar;
private MaterialTextView textView_noData;
private RecyclerView recyclerView;
private List<SubCategoryList> relatedLists;
private SubCategoryAdapter subCategoryAdapter;
private LayoutAnimationController animation;
private Boolean isOver = false;
private int pagination_index = 1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.portrait_fragment, container, false);
GlobalBus.getBus().register(this);
MainActivity.toolbar.setTitle(getResources().getString(R.string.related_status));
relatedLists = new ArrayList<>();
onClick = new OnClick() {
#Override
public void position(int position, String title, String type, String status_type, String id, String tag) {
SCDetailFragment scDetailFragment = new SCDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("type", type);
bundle.putString("status_type", status_type);
bundle.putInt("position", position);
scDetailFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, scDetailFragment, title).addToBackStack(title).commitAllowingStateLoss();
}
};
method = new Method(getActivity(), onClick);
assert getArguments() != null;
type = getArguments().getString("type");
post_id = getArguments().getString("post_id");
cat_id = getArguments().getString("cat_id");
typeLayout = getArguments().getString("typeLayout");
int resId = R.anim.layout_animation_fall_down;
animation = AnimationUtils.loadLayoutAnimation(getActivity(), resId);
progressBar = view.findViewById(R.id.progressbar_portrait_fragment);
textView_noData = view.findViewById(R.id.textView_portrait_fragment);
recyclerView = view.findViewById(R.id.recyclerView_portrait_fragment);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
if (!isOver) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pagination_index++;
callData();
}
}, 1000);
} else {
subCategoryAdapter.hideHeader();
}
}
});
callData();
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.ic_searchView);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener((new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (method.isNetworkAvailable()) {
backStackRemove();
SearchFragment searchFragment = new SearchFragment();
Bundle bundle = new Bundle();
bundle.putString("search_menu", query);
bundle.putString("typeLayout", "Landscape");
searchFragment.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.frameLayout_main, searchFragment, query).commitAllowingStateLoss();
return false;
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
}));
super.onCreateOptionsMenu(menu, inflater);
}
private void backStackRemove() {
for (int i = 0; i < getActivity().getSupportFragmentManager().getBackStackEntryCount(); i++) {
getActivity().getSupportFragmentManager().popBackStack();
}
}
#Subscribe
public void getNotify(Events.FavouriteNotify favouriteNotify) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(favouriteNotify.getId())) {
if (relatedLists.get(i).getStatus_type().equals(favouriteNotify.getStatus_type())) {
relatedLists.get(i).setIs_favourite(favouriteNotify.getIs_favourite());
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
#Subscribe
public void getMessage(Events.InfoUpdate infoUpdate) {
if (subCategoryAdapter != null) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(infoUpdate.getId())) {
if (relatedLists.get(i).getStatus_type().equals(infoUpdate.getStatus_type())) {
switch (infoUpdate.getType()) {
case "all":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
case "view":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
break;
case "like":
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
}
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
}
private void callData() {
if (getActivity() != null) {
if (method.isNetworkAvailable()) {
if (method.pref.getBoolean(method.pref_login, false)) {
related(method.pref.getString(method.profileId, null), post_id, cat_id, typeLayout);
} else {
related("0", post_id, cat_id, typeLayout);
}
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
}
}
private void related(String userId, String post_id, String cat_id, String typeLayout) {
if (subCategoryAdapter == null) {
relatedLists.clear();
progressBar.setVisibility(View.VISIBLE);
}
if (getActivity() != null) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API(getActivity()));
jsObj.addProperty("method_name", "related_status");
jsObj.addProperty("post_id", post_id);
jsObj.addProperty("cat_id", cat_id);
jsObj.addProperty("user_id", userId);
jsObj.addProperty("page", pagination_index);
jsObj.addProperty("filter_value", typeLayout);
jsObj.addProperty("lang_ids", method.pref.getString(method.language_ids, ""));
params.put("data", API.toBase64(jsObj.toString()));
client.post(Constant_Api.url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (getActivity() != null) {
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
if (jsonObject.has(Constant_Api.STATUS)) {
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("-2")) {
method.suspend(message);
} else {
method.alertBox(message);
}
} else {
JSONArray jsonArray = jsonObject.getJSONArray(Constant_Api.tag);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String status_type = object.getString("status_type");
String status_title = object.getString("status_title");
String status_layout = object.getString("status_layout");
String status_thumbnail_b = object.getString("status_thumbnail_b");
String status_thumbnail_s = object.getString("status_thumbnail_s");
String total_likes = object.getString("total_likes");
String total_viewer = object.getString("total_viewer");
String category_name = object.getString("category_name");
String already_like = object.getString("already_like");
String quote_bg = object.getString("quote_bg");
String quote_font = object.getString("quote_font");
String is_favourite = object.getString("is_favourite");
relatedLists.add(new SubCategoryList("", id, status_type, status_title, status_layout, status_thumbnail_b, status_thumbnail_s, total_viewer, total_likes, already_like, category_name, quote_bg, quote_font, is_favourite, "", ""));
}
if (jsonArray.length() == 0) {
if (subCategoryAdapter != null) {
isOver = true;
subCategoryAdapter.hideHeader();
}
}
if (subCategoryAdapter == null) {
if (relatedLists.size() == 0) {
textView_noData.setVisibility(View.VISIBLE);
} else {
textView_noData.setVisibility(View.GONE);
subCategoryAdapter = new SubCategoryAdapter(getActivity(), relatedLists, onClick, type);
recyclerView.setAdapter(subCategoryAdapter);
recyclerView.setLayoutAnimation(animation);
}
} else {
subCategoryAdapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
method.alertBox(getResources().getString(R.string.failed_try_again));
}
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
progressBar.setVisibility(View.GONE);
method.alertBox(getResources().getString(R.string.failed_try_again));
}
});
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
GlobalBus.getBus().unregister(this);
}
}
Adapter
public class SubCategoryAdapter extends RecyclerView.Adapter {
private Activity activity;
private Method method;
private int columnWidth;
private String type;
private Animation myAnim;
private List<SubCategoryList> subCategoryLists;
private final int VIEW_TYPE_LOADING = 0;
private final int VIEW_TYPE_ITEM = 1;
private final int VIEW_TYPE_QUOTES = 2;
public SubCategoryAdapter(Activity activity, List<SubCategoryList> subCategoryLists, OnClick interstitialAdView, String type) {
this.activity = activity;
this.type = type;
this.subCategoryLists = subCategoryLists;
method = new Method(activity, interstitialAdView);
columnWidth = (method.getScreenWidth());
myAnim = AnimationUtils.loadAnimation(activity, R.anim.bounce);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(activity).inflate(R.layout.sub_category_adapter, parent, false);
return new ViewHolder(view);
} else if (viewType == VIEW_TYPE_QUOTES) {
View v = LayoutInflater.from(activity).inflate(R.layout.quotes_adapter, parent, false);
return new Quotes(v);
} else if (viewType == VIEW_TYPE_LOADING) {
View v = LayoutInflater.from(activity).inflate(R.layout.layout_loading_item, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") final int position) {
if (holder.getItemViewType() == VIEW_TYPE_ITEM) {
final ViewHolder viewHolder = (ViewHolder) holder;
if (status_type.equals("gif")) {
Glide.with(activity)
.asBitmap()
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
} else {
Glide.with(activity)
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
}
viewHolder.imageView.setLayoutParams(new RelativeLayout.LayoutParams(columnWidth, columnWidth / 2 - 60));
viewHolder.textView_title.setText(subCategoryLists.get(position).getStatus_title());
viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
} else if (holder.getItemViewType() == VIEW_TYPE_QUOTES) {
final Quotes quotes = (Quotes) holder;
quotes.relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, columnWidth / 2));
Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "text_font/" + subCategoryLists.get(position).getQuote_font());
quotes.textView.setTypeface(typeface);
quotes.textView.setText(subCategoryLists.get(position).getStatus_title());
quotes.textView.post(new Runnable() {
#Override
public void run() {
ViewGroup.LayoutParams params = quotes.textView.getLayoutParams();
if (params == null) {
params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
final int widthSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getWidth(), View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getHeight(), View.MeasureSpec.UNSPECIFIED);
quotes.textView.measure(widthSpec, heightSpec);
quotes.textView.setMaxLines(heightSpec / quotes.textView.getLineHeight());
quotes.textView.setEllipsize(TextUtils.TruncateAt.END);
}
});
quotes.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
}
}
#Override
public int getItemCount() {
return subCategoryLists.size() + 1;
}
public void hideHeader() {
ProgressViewHolder.progressBar.setVisibility(View.GONE);
}
#Override
public int getItemViewType(int position) {
if (position != subCategoryLists.size()) {
if (subCategoryLists.get(position).getStatus_type().equals("quote")) {
return VIEW_TYPE_QUOTES;
} else {
return VIEW_TYPE_ITEM;
}
} else {
return VIEW_TYPE_LOADING;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout relativeLayout;
private ImageView imageView;
private MaterialTextView textView_title;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.relativeLayout_subCat_adapter);
imageView = itemView.findViewById(R.id.imageView_subCat_adapter);
textView_title = itemView.findViewById(R.id.textView_title_subCat_adapter);
}
}
public class Quotes extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private RelativeLayout relativeLayout;
private MaterialTextView textView;
public Quotes(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.ll_quotes_adapter);
textView = itemView.findViewById(R.id.textView_quotes_adapter);
relativeLayout = itemView.findViewById(R.id.rel_quotes_adapter);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public static ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = v.findViewById(R.id.progressBar);
}
} }

How can I limit the number of native ads in recyclerview

How can I limit the number of native ads in recyclerview
I only want 5 native ads in first 100 lines in recyclerview (per every 20 lines).
My recyclerview have got 10000 row. It annoys the user on every 20 lines of ad output. So I want to limit the number of ads to 5. I made a lot of changes, but I could not.
Thank you in advance for your help
advertising related section in my activity
public static final int ITEMS_PER_AD = 20;
private static final int NATIVE_EXPRESS_AD_HEIGHT = 100;
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 <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = new NativeExpressAdView(getActivity());
mRecyclerViewItems.add(i, adView);
}
}
private void setUpAndLoadNativeExpressAds() {
mRecyclerView.post(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
AdSize adSize = new AdSize(AdSize.FULL_WIDTH, NATIVE_EXPRESS_AD_HEIGHT);
adView.setAdSize(adSize);
adView.setAdUnitId(AD_UNIT_ID);
}
loadNativeExpressAd(0);
}catch (Exception e){
}
}
});
}
private void loadNativeExpressAd(final int index) {
// if (index >= mRecyclerViewItems.size()) {
// return;
// }
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 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.
if (index<24){
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);
}
});
try {
adView.loadAd(new AdRequest.Builder().build());
}catch (Exception e){}
}
and my RecyclerViewAdapter.java
class RecyclerViewAdapter extends FastScrollRecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
private final Context mContext;
private final List<Object> mRecyclerViewItems;
ItemClickListener listener;
public RecyclerViewAdapter(Context context, List<Object> recyclerViewItems, ItemClickListener listener) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
this.listener=listener;
}
public class MenuItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView menuItemName;
private TextView menuItemDescription;
private TextView menuItemPrice;
private TextView menuItemCategory;
private ImageView menuItemImage;
ItemClickListener itemClickListener;
MenuItemViewHolder(View view) {
super(view);
menuItemImage = (ImageView) view.findViewById(R.id.cinsiyetresmi);
menuItemName = (TextView) view.findViewById(R.id.menu_item_name);
menuItemPrice = (TextView) view.findViewById(R.id.menu_item_price);
menuItemCategory = (TextView) view.findViewById(R.id.menu_item_category);
menuItemDescription = (TextView) view.findViewById(R.id.menu_item_description);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
}
public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder {
NativeExpressAdViewHolder(View view) {
super(view);
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
#Override
public int getItemViewType(int position) {
return (position % isimler_erkek.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.menu_item_container, viewGroup, false);
return new MenuItemViewHolder(menuItemLayoutView);
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// 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(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
MenuItem menuItem;
MenuItemViewHolder menuItemHolder;
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
menuItemHolder = (MenuItemViewHolder) holder;
menuItem = (MenuItem) mRecyclerViewItems.get(position);
// Get the menu item image resource ID.
String imageName = menuItem.getImageName();
int imageResID = mContext.getResources().getIdentifier(imageName, "drawable",
mContext.getPackageName());
// Add the menu item details to the menu item view.
menuItemHolder.menuItemImage.setImageResource(imageResID);
menuItemHolder.menuItemName.setText(menuItem.getName());
menuItemHolder.menuItemPrice.setText(menuItem.getPrice());
menuItemHolder.menuItemCategory.setText(menuItem.getCategory());
menuItemHolder.menuItemDescription.setText(menuItem.getDescription());
final int idsi= Integer.parseInt(menuItem.getDescription());
menuItemHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
//Snackbar.make(v,String.valueOf(players.get(pos).getId()), Snackbar.LENGTH_SHORT).show();
try {
listener.onItemClick(v,idsi);
}
catch (Exception e){
}
//Toast.makeText(this.getApplicationContext(), "bak", Toast.LENGTH_LONG).show();
}
});
break;
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
NativeExpressAdViewHolder nativeExpressHolder =
(NativeExpressAdViewHolder) holder;
NativeExpressAdView adView =
(NativeExpressAdView) mRecyclerViewItems.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Add the Native Express ad to the native express ad view.
adCardView.addView(adView);
}
}
}
private View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterVideo mAdapter;
private SwipeRefreshLayout swipe_refresh;
private Call<CallbackRecent> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
int counter = 1;
private List<Object> ViewItems = new ArrayList<>();
// List of native ads that have been successfully loaded.
private List<UnifiedNativeAd> mNativeAds = new ArrayList<>();
// The AdLoader used to load ads.
private AdLoader adLoader;
// The number of native ads to load.
public static final int NUMBER_OF_ADS = 4;
// The number of Items to Show Native Between Items.
public static final int NUMBER_OF_ROW = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_video, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
// Update the RecyclerView item's list with native ads.
loadNativeAds();
swipe_refresh = root_view.findViewById(R.id.swipe_refresh_layout_home);
swipe_refresh.setColorSchemeResources(R.color.colorOrange, R.color.colorGreen, R.color.colorBlue, R.color.colorRed);
recyclerView = root_view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
// mAdapter = new AdapterVideo(getActivity(), recyclerView, new ArrayList<News>());
mAdapter = new AdapterVideo(getActivity(), recyclerView, ViewItems);
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if (Config.ENABLE_RTL_MODE) {
recyclerView.setRotationY(180);
}
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterVideo.OnItemClickListener() {
#Override
public void onItemClick(View v, News obj, int position) {
ActivityNewsDetail.navigate((MainActivity) getActivity(), v.findViewById(R.id.image), obj);
showInterstitialAd();
}
});
// detect when scroll reach bottom
mAdapter.setOnLoadMoreListener(new AdapterVideo.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > mAdapter.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
mAdapter.setLoaded();
}
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
mAdapter.resetListData();
requestAction(1);
}
});
requestAction(1);
getAllVideo();
return root_view;
}
private void getAllVideo(){
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
mAdapter.resetListData();
requestAction(1);
}
private void displayApiResult(final List<News> posts) {
mAdapter.insertData(posts);
swipeProgress(false);
if (posts.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getVideoPost(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackRecent>() {
#Override
public void onResponse(Call<CallbackRecent> call, Response<CallbackRecent> response) {
CallbackRecent resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackRecent> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
mAdapter.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.msg_no_network));
} else {
showFailedView(true, getString(R.string.msg_offline));
}
}
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
mAdapter.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
root_view.findViewById(R.id.failed_retry).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.msg_no_news);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
MobileAds.initialize(getActivity(), getResources().getString(R.string.admob_app_id));
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(Tools.getAdRequest(getActivity()));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
}
}
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(getActivity(), getString(R.string.admob_native_unit_id));
adLoader = builder.forUnifiedNativeAd(
new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// A native ad loaded successfully
mNativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsInMenuItems(); //Show Native Inside Items RecyclerView
}
}
}).withAdListener(
new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
// A native ad failed to load, check if the ad loader has finished loading
Log.e("MainActivity", "The previous native ad failed to load. Attempting to"
+ " load another.");
if (!adLoader.isLoading()) {
insertAdsInMenuItems(); //Show Native Inside Items RecyclerView
}
}
}).build();
// Load the Native ads.
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS);
}
// Method To Add native Inside Items :
private void insertAdsInMenuItems() {
if (mNativeAds.size() <= 0) {
return;
}
int offset = (ViewItems.size() / mNativeAds.size()) + NUMBER_OF_ROW;
int index = 0;
for (UnifiedNativeAd ad : mNativeAds) {
ViewItems.add(index, ad);
index = index + offset;
}
}

Un-filtering the result is not working in Recyclerview

I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}

RecyclerView fling and move not smooth

i am chinese coder.i am not good at english,so just try hard to describe the question. thank you very much for your answer.
when i first into activity with RecyclerView and scroll,it is not smooth especially showing next item next ,but when i have scrolled the Recyclerview,it is work,and smooth . some coder say we can't do much work on onCreateViewHolder() and onBindViewHolder() , but i can not get it.
here is my code:
fragment
public class HomeFragment extends RefreshableFragment implements IHomeView {
#Bind(R.id.refresh_view)
PullToRefreshRecyclerView refresh_view;
private RecyclerView refreshableView;
private HomePresenter homePresenter;
#Override
public View initSuccessView() {
View view = View.inflate(getContext(), R.layout.fragment_refreshable_success_recyclerview, null);
ButterKnife.bind(this, view);
initRefreshLayout();
initRecyclerView();
return view;
}
/**
* 初始化可刷新控件
*/
private void initRefreshLayout() {
refresh_view.setMode(PullToRefreshBase.Mode.BOTH);
refresh_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.refresh();
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.loadMore();
}
});
}
/**
* 初始化RecyclerView控件
*/
private void initRecyclerView() {
refreshableView = refresh_view.getRefreshableView();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
SpaceItemDecoration decor = new SpaceItemDecoration(2);
refreshableView.addItemDecoration(decor);
refreshableView.setLayoutManager(layoutManager);
refreshableView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int childCount = recyclerView.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = recyclerView.getChildAt(i);
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(view);
switch (holder.getItemViewType()){
case HomeAdapter.TYPE_TOPIC:
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setParentHeight(recyclerView.getHeight());
topicViewHolder.setOffset();
}
}
}
});
}
#Override
protected void requestNetwork() {
homePresenter = new HomePresenter(getContext(),this,null);
homePresenter.init();
}
#Override
public RecyclerView getRecyclerView() {
return refreshableView;
}
#Override
public RefreshView getRefreshView() {
return getParentRefreshView();
}
#Override
public void onRefreshFinish() {
if(refresh_view.isRefreshing()){
refresh_view.onRefreshComplete();
}
}
#Override
public void onLordMoreFinish() {
}
}
presenter
public class HomePresenter extends BasePresenter<IHomeView> implements IHomePresenter, StringLoaderCallback {
private Gson gson;
private HomeAdapter homeAdapter;
private final Pagination pagination;
public HomePresenter(Context context,IHomeView homeView,Bundle bundle) {
super(context,homeView,bundle);
gson = new Gson();
homeAdapter = new HomeAdapter();
getPresenterView().getRecyclerView().setAdapter(homeAdapter);
pagination = new Pagination();
pagination.setLimit(10);
pagination.setOffset(0);
}
#Override
public void init() {
String bannerUrl = ServerAPI.Home.buildHomeBannerUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(bannerUrl, null, bannerUrl, this);
String topicUrl = ServerAPI.Home.buildHomeTopicUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(topicUrl, null, topicUrl, this);
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), REFRESH, this);
}
#Override
public void loadMore() {
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
pagination.setOffset(pagination.getTotal());
pagination.setLimit(10);
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), LOADMORE, this);
}
#Override
public void refresh() {
pagination.setOffset(0);
pagination.setLimit(10);
pagination.clearTotal();
init();
}
#Override
public void onLoadFinished(String url,Map<String,String> params, String data,Object tag) {
if(url.equals(ServerAPI.Home.buildHomeBannerUrl())){
Log.i(url,data);
HomeBanner.HomeBannerLists homeBannerLists = gson.fromJson(data,HomeBanner.HomeBannerLists.class);
homeAdapter.setBanners(homeBannerLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeTopicUrl())){
Log.i(url,data);
HomeTopic.HomeTopicLists homeTopicLists = gson.fromJson(data,HomeTopic.HomeTopicLists.class);
homeAdapter.setTopics(homeTopicLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeRouteUrl())){
Log.i(url,data);
int mode = (int) tag;
HomeRoute.HomeRouteLists homeRouteLists = gson.fromJson(data, HomeRoute.HomeRouteLists.class);
if (mode == REFRESH){
homeAdapter.setRoutes(homeRouteLists.list);
} else if(mode == LOADMORE){
homeAdapter.appendRoutes(homeRouteLists.list);
}
pagination.appendTotal(homeRouteLists.list.size());
}
getPresenterView().getRefreshView().setCurrentState(RefreshView.STATE_SUCCESS);
getPresenterView().onRefreshFinish();
}
#Override
public void onLoadError(VolleyError error) {
Log.i("error",error.getMessage());
}
}
adapter
public class HomeAdapter extends RecyclerView.Adapter {
public static final int TYPE_BANNER = 0;
public static final int TYPE_TOPIC = 1;
public static final int TYPE_ROUTE = 2;
private List<HomeBanner> banners = new ArrayList<>();
private List<HomeTopic> topics = new ArrayList<>();
private List<HomeRoute> routes = new ArrayList<>();
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case TYPE_BANNER:
View bannerView = HomeBannerViewHolder.getView(parent.getContext());
return new HomeBannerViewHolder(bannerView);
case TYPE_TOPIC:
View topicView = View.inflate(parent.getContext(), R.layout.item_home_topic,null);
// View topicView = HomeTopicViewHolder.getView(parent.getContext());
return new HomeTopicViewHolder(topicView);
case TYPE_ROUTE:
View routeView = View.inflate(parent.getContext(), R.layout.item_home_route,null);
// View routeView = HomeRouteViewHolder.getView(parent.getContext());
return new HomeRouteViewHolder(routeView);
default:
// View defaultView = new View(parent.getContext());
View view = EmptyViewHolder.getView(parent.getContext());
return new EmptyViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(position == 0){
onBindBannerViewHolder(holder);
}else if(position>0 && position<topics.size()+1){
onBindTopicViewHolder(holder,position-1);
}else {
onBindRouteViewHolder(holder,position-topics.size()-1);
}
}
private void onBindRouteViewHolder(RecyclerView.ViewHolder holder, int position) {
HomeRouteViewHolder routeViewHolder = (HomeRouteViewHolder) holder;
routeViewHolder.setData(routes.get(position));
}
private void onBindTopicViewHolder(RecyclerView.ViewHolder holder,int position) {
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setData(topics.get(position));
}
private void onBindBannerViewHolder(RecyclerView.ViewHolder holder) {
HomeBannerViewHolder bannerViewHolder = (HomeBannerViewHolder) holder;
bannerViewHolder.setData(banners);
}
#Override
public int getItemCount() {
return 1 + topics.size()+routes.size();
}
#Override
public int getItemViewType(int position) {
if(position == 0){
return TYPE_BANNER;
}else if(position<topics.size()+1){
return TYPE_TOPIC;
}else {
return TYPE_ROUTE;
}
}
public void setBanners(List<HomeBanner> list){
banners.clear();
banners.addAll(list);
notifyDataSetChanged();
}
public void setTopics(List<HomeTopic> list) {
topics.clear();
topics.addAll(list);
notifyDataSetChanged();
}
public void setRoutes(List<HomeRoute> list) {
routes.clear();
routes.addAll(list);
notifyDataSetChanged();
}
public void appendRoutes(List<HomeRoute> list) {
routes.addAll(routes.size(),list);
notifyItemRangeInserted(getItemCount(),list.size());
}
}
holder
public class HomeTopicViewHolder extends BaseViewHolder<HomeTopic> {
private static SimpleDraweeView content_iv ;
private static TextView home_topic_title ;
private static TextView home_topic_discription ;
private int height;
public static View getView(Context context) {
View topicView = View.inflate(context, R.layout.item_home_topic,null);
return topicView;
}
public HomeTopicViewHolder(View itemView) {
super(itemView);
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
if(content_iv!=null){
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
}
if(home_topic_title!=null){
home_topic_title = (TextView) itemView.findViewById(R.id.home_topic_title);
}
if(home_topic_discription!=null){
home_topic_discription = (TextView) itemView.findViewById(R.id.home_topic_discription);
}
if(height==0){
SharedPreferences sp = SharedPreferenceHelper.getInstance().getSharedPreference(itemView.getContext(), SharedPreferenceHelper.EnumSPName.CONFIG);
int scale = sp.getInt(SharedPreferenceHelper.EnumSPName.windowWidth, 0);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(scale,scale);
content_iv.setLayoutParams(layoutParams);
}
}
#Override
protected void inflateView(HomeTopic data) {
NetworkImageLoader loader = NetworkImageLoader.getInstance();
loader.setUrlToSimpleDraweeView(data.getImage(),content_iv);
home_topic_title.setText(data.getName());
home_topic_discription.setText(String.format(getResources().getString(R.string.guider_route),data.getGuide(), data.getRoute()));
}
public void setOffset() {
int itemViewHeight = itemView.getHeight();
int imageViewHeight = content_iv.getHeight();
int parentOffsetMax = (getParentHeight() + itemViewHeight) / 2;
int offsetMax = imageViewHeight - itemViewHeight;
float y = itemView.getY();
float location = y + itemViewHeight/2;
float v = location - getParentHeight() / 2;
float percent = v/parentOffsetMax;
int margin = (int) ((offsetMax/2)*(percent + 1));
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) content_iv.getLayoutParams();
layoutParams.setMargins(0,-margin,0,0);
content_iv.setLayoutParams(layoutParams);
}
public void setParentHeight(int height) {
this.height = height;
}
public int getParentHeight() {
return height;
}
}

Categories

Resources