recyclerview adapter notifydatasetchanged not work - android

when i just use the imageRecyclerViewAdapter.notifyDataSetChanged(); it did not work anyway.
imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this,imagesList);
recyclerView.setAdapter(imageRecyclerViewAdapter);
if i did this , it will be work.
so how should i do .
my code following.
public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public static final int TYPE_ITEM = 0;
public static final int TYPE_FOOTER = 1;
private boolean hasFooter;//设置是否显示Footer
private boolean hasMoreData;//设置是否可以继续加载数据
private List<ImageFuli> images;
private Context context;
public ImageRecyclerViewAdapter(Context context, List<ImageFuli> images) {
this.images = images;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_FOOTER){//底部 加载view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_progress, parent, false);
return new FooterViewHolder(view);
} else {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_list, null);
ImageViewHolder ivh = new ImageViewHolder(layoutView);
return ivh;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof FooterViewHolder) {
if(hasMoreData){
((FooterViewHolder) holder).mProgressView.setVisibility(View.VISIBLE);
} else {
((FooterViewHolder) holder).mProgressView.setVisibility(View.GONE);
}
} else {
ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
ImageFuli imageFuli= images.get(position);
imageViewHolder.imageView.setOriginalSize(imageFuli.getWidth(), imageFuli.getHeight());
Glide.with(context)
.load(imageFuli.getUrl())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewHolder.imageView);
ViewCompat.setTransitionName(imageViewHolder.imageView,imageFuli.getUrl());
}
}
#Override
public int getItemCount() {
return this.images.size() + (hasFooter ? 1 : 0);
}
#Override
public int getItemViewType(int position) {
if (position == getBasicItemCount() && hasFooter) {
return TYPE_FOOTER;
}
return TYPE_ITEM;//0
}
private int getBasicItemCount() {
return images.size();
}
public boolean hasFooter() {
return hasFooter;
}
public void setHasFooter(boolean hasFooter) {
if(this.hasFooter != hasFooter) {
this.hasFooter = hasFooter;
notifyDataSetChanged();
}
}
public boolean hasMoreData() {
return hasMoreData;
}
public void setHasMoreData(boolean isMoreData) {
if(this.hasMoreData != isMoreData) {
this.hasMoreData = isMoreData;
notifyDataSetChanged();
}
}
public void setHasMoreDataAndFooter(boolean hasMoreData, boolean hasFooter) {
if(this.hasMoreData != hasMoreData || this.hasFooter != hasFooter) {
this.hasMoreData = hasMoreData;
this.hasFooter = hasFooter;
notifyDataSetChanged();
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
private RatioImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
imageView = (RatioImageView) itemView.findViewById(R.id.image);
}
}
public class FooterViewHolder extends RecyclerView.ViewHolder {
public final View mProgressView;
public FooterViewHolder(View view) {
super(view);
mProgressView = View.inflate(context,R.layout.footer_progress, null);
}
}
}
and the mainActivity
public class MainActivity extends AppCompatActivity {
private StaggeredGridLayoutManager gaggeredGridLayoutManager;
private List<ImageFuli> imagesList = new ArrayList<ImageFuli>();
private ImageRecyclerViewAdapter imageRecyclerViewAdapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean onLoading = false;
private int loadImageCount = 15;
private int loadTimes=1;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getImagesDataFromHttp();
}
private void init() {
recyclerView = (RecyclerView)findViewById(R.id.content);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresher);
swipeRefreshLayout.setColorSchemeColors(R.color.colorPrimary);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImagesDataFromHttp();
}
});
recyclerView.setHasFixedSize(true);
imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this, imagesList);
recyclerView.setAdapter(imageRecyclerViewAdapter);
gaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1);
recyclerView.setLayoutManager(gaggeredGridLayoutManager);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
private void getImagesDataFromHttp() {
HttpUtil.httpRequestToGank(ApiUrl.gankApiUrl+(loadImageCount+5*loadTimes)+"/1" , new HttpUtil.HttpUtilCallBack() {
#Override
public void onFinsh(String response) {
try {
imagesList = ResponseHandleUtil.HandleResponseFromHttp(response, MainActivity.this);
loadTimes++;
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this, imagesList);
// recyclerView.setAdapter(imageRecyclerViewAdapter);
//imageRecyclerViewAdapter.notifyDataSetChanged();
recyclerView.getAdapter().notifyDataSetChanged();
imageRecyclerViewAdapter.setHasFooter(false);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
#Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
});
}
}

get the adapter of your recyclerview
mRecyclerView.getAdapter().notifyDataSetChanged();

because i change the imagelist's reference .so adapter.notifyDataSetChanged can not work any more.

Related

When I Enable Slider in Adapter Last position not showing (SLIDER_VIEW merge with ITEM_VIEW )

Need to Show Slider With a missing fisrt position of ITEM_VIEW
Check IMAGE 1
When Slider Enabled Don't Showing first position of ITEM_VIEW (Issue is SLIDER_VIEW position merge with ITEM_VIEW position). Need to show ITEM_VIEW missing first position With Slider
Check IMAGE 2
When Slider Not Enabled ITEM_VIEW first position Showing
public class WallpapersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM_VIEW = 0;
private static final int AD_VIEW = 1;
private static final int SLIDER_VIEW = 2;
public static SharedPreferences sharedPreferences;
final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 6000; // time in milliseconds between successive task executions.
private final Context mContext;
private final OnItemClickListener listener;
private final int itemLayout;
public List<Image> mData;
RequestOptions option;
SharedPref sharedPref;
String status;
List<SliderUtils> sliderImg;
ViewPagerAdapterSlider viewPagerAdapterSlider;
int currentPage = 1;
Timer timer;
private int dotscount;
private ImageView[] dots;
public WallpapersAdapter(Context mContext, List<Image> mData, OnItemClickListener listener) {
this.mContext = mContext;
this.mData = mData;
this.listener = listener;
this.itemLayout = R.layout.wallpaper_item;
// Request option for Glide
option = new RequestOptions().centerCrop();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
if (viewType == ITEM_VIEW) {
View view = layoutInflater.inflate(R.layout.wallpaper_item, parent, false);
return new MainViewHolder(view);
} else if (viewType == AD_VIEW) {
View view = layoutInflater.inflate(R.layout.item_native_ad, parent, false);
return new AdViewHolder(view);
} else if (viewType == SLIDER_VIEW) {
View view = layoutInflater.inflate(R.layout.custom_layout, parent, false);
return new SliderViewHolder(view);
} else {
return null;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
status = sharedPreferences.getString("status", "free");
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
if (holder.getItemViewType() == ITEM_VIEW) {
int pos = position - Math.round(position / Config.NATIVE_ADS_PER_ITEM);
((MainViewHolder) holder).bindData(mData.get(pos), listener, position);
} else if (holder.getItemViewType() == AD_VIEW) {
if (Config.ENABLE_ADS == true & status.equals("free")) {
((AdViewHolder) holder).bindAdData();
layoutParams.setFullSpan(getItemViewType(position) == AD_VIEW);
}
} else if (holder.getItemViewType() == SLIDER_VIEW) {
layoutParams.setFullSpan(getItemViewType(position) == SLIDER_VIEW);
((SliderViewHolder) holder).bindSliderData();
}
}
#Override
public int getItemCount() {
if (mData.size() > 0) {
return mData.size() + Math.round(mData.size() / Config.NATIVE_ADS_PER_ITEM);
}
return mData.size();
}
#Override
public int getItemViewType(int position) {
// Here position set 0 showing Slider But not showing last position
if ((position == 0) && Config.ENABLE_RECENT_SLIDER == true) {
return SLIDER_VIEW;
} else if ((position + 1) % Config.NATIVE_ADS_PER_ITEM == 0) {
return AD_VIEW;
}
return ITEM_VIEW;
}
private void sendRequest(ViewPager viewPagerForSlider, TextView textSlider) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Config.SM, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja_data = response.getJSONArray("slides");
Log.d("OHOHOH", String.valueOf(ja_data));
for (int i = 0; i < ja_data.length(); i++) {
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = ja_data.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("slider_image"));
sliderUtils.setUrl(jsonObject.getString("url"));
sliderUtils.setSlider_name(jsonObject.getString("slider_name"));
sliderUtils.setType(jsonObject.getString("slider_type"));
sliderUtils.setCat_id(jsonObject.getInt("cat_id"));
sliderUtils.setCollection(jsonObject.getString("collection"));
//textSlider.setText(jsonObject.getString("slider_name"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapterSlider = new ViewPagerAdapterSlider(sliderImg, mContext);
viewPagerForSlider.setAdapter(viewPagerAdapterSlider);
dotscount = viewPagerAdapterSlider.getCount();
dots = new ImageView[dotscount];
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == dotscount) {
currentPage = 0;
}
viewPagerForSlider.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MySingleton.getInstance(mContext).addToRequestQueue(request);
}
public interface OnItemClickListener {
void onItemClick(View view, Image mData, int position);
}
public class MainViewHolder extends RecyclerView.ViewHolder {
WallpaperItemBinding binding;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
binding = WallpaperItemBinding.bind(itemView);
}
public void bindData(Image main, final OnItemClickListener listener, final int position) {
sharedPref = new SharedPref(mContext);
binding.wallpaperName.setText(main.getImage_name());
binding.viewCount.setText(main.getViews_count());
if (sharedPref.loadAmoled() == true) {
binding.constraintBg.setBackgroundColor(mContext.getResources().getColor(R.color.amoled_color_light));
}
sharedPref = new SharedPref(mContext);
}
}
public class AdViewHolder extends RecyclerView.ViewHolder {
ItemNativeAdBinding binding;
public AdViewHolder(#NonNull View itemView) {
super(itemView);
binding = ItemNativeAdBinding.bind(itemView);
}
#SuppressLint("MissingPermission")
private void bindAdData() {
final AdLoader adLoader = new AdLoader.Builder(mContext, mContext.getResources().getString(R.string.admob_native_id))
.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
#Override
public void onNativeAdLoaded(NativeAd ad) {
binding.admobNativeAdContainer.setNativeAd(ad);
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(), 3);
if (isNetworkConnected()) {
binding.admobNativeAdContainer.setVisibility(View.VISIBLE);
}
}
#SuppressLint("MissingPermission")
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
}
public class SliderViewHolder extends RecyclerView.ViewHolder {
CustomLayoutBinding customLayoutBinding;
public SliderViewHolder(View view) {
super(view);
customLayoutBinding = CustomLayoutBinding.bind(view);
}
public void bindSliderData() {
sliderImg = new ArrayList<>();
customLayoutBinding.viewPagerForSlider.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
customLayoutBinding.dotsIndicator.setViewPager(customLayoutBinding.viewPagerForSlider);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
sendRequest(customLayoutBinding.viewPagerForSlider, customLayoutBinding.textSlider);
}
}
}

how to remove all items from RecyclerView on toolbar icon delete in android

Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}

How to make TimeLine just like Instagram with multiple Images and Video and Autoplay Back?

I am implementing Timeline just like Instagram, but i have multiple tabs as i mentioned in the picture. and each tab have separate fragments. Each single fragment have a RecyclerView for multiple Post and i made an adapter for rendering list. i passed the list in adapter and each post item can have multiple images and videos so i make another RecyclerView in single_post_item and made another Adapter for rendering post media. I made a single View Holder for multiple post in first adapter and then i called another adapter from that ViewHolder. In Post Media Adapter i made two view holders one for Images and Other for Videos. i used Exo Player in for playing Videos. the thing which is not resolving is that if i have videos in two consecutive post items it playing video for both items. so how can i handle this scenario. Waiting for the great response from you guys. Thanks in Advance
AllStoriesFragment.java
public class AllStoriesFragment extends DaggerFragment implements OnStoryFetchListener {
private HomeActivity activity;
private FragmentAllStoriesBinding binding;
private List<StoriesResponse> storiesResponseList=new ArrayList<>();
private AllStoriesAdapter adapter;
private List<MediaAttachment> mediaAttachments=new ArrayList<>();
#Inject
StoriesRepository storiesRepository;
private List<Stories> allStoriesList = new ArrayList<>();
private List<StoriesMediaItems> storiesMediaItems=new ArrayList<>();
private Boolean scrollToTop = false;
#Inject
TTViewModelFactory viewModelFactory;
StoriesViewModel storiesViewModel;
private LinearLayoutManager linearLayoutManager;
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (HomeActivity) context;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_all_stories, container, false);
return binding.getRoot();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
storiesViewModel= ViewModelProviders.of(this, viewModelFactory).get(StoriesViewModel.class);
storiesViewModel.getLatestAllStories(0, AllStoriesFragment.this);
storiesViewModel.getAllStories().observe(this,stories -> {
if (storiesResponseList == null || adapter == null) {
setAdapter();
}
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new StoriesDiffCallback(allStoriesList, stories));
diffResult.dispatchUpdatesTo(adapter);
storiesResponseList.clear();
allStoriesList.clear();
//allStoriesList.addAll(stories != null ? stories : new ArrayList<>());
allStoriesList = stories;
for (int i=0;i<allStoriesList.size();i++){
storiesMediaItems = storiesViewModel.getAllStoryMedia(allStoriesList.get(i).getId());
storiesResponseList.add(new StoriesResponse(allStoriesList.get(i).getPostedBy(),allStoriesList.get(i).getPostedByName(),allStoriesList.get(i).getId(),allStoriesList.get(i).getLikesCount(),allStoriesList.get(i).getCommentsCount(),allStoriesList.get(i).getShareCount(),allStoriesList.get(i).getTimeStamp(),allStoriesList.get(i).getLiked(),storiesMediaItems));
}
if(adapter == null){
setAdapter();
}
else {
adapter.notifyDataSetChanged();
}
if (scrollToTop) {
if (storiesResponseList.size() > 0) {
binding.allStoriesListView.scrollToPosition(0);
}
scrollToTop = false;
}
});
}
private void setAdapter(){
if (storiesResponseList == null) {
this.storiesResponseList = new ArrayList<>();
}
linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
binding.allStoriesListView.setLayoutManager(linearLayoutManager);
binding.allStoriesListView.setItemViewCacheSize(0);
adapter= new AllStoriesAdapter(activity,activity,getChildFragmentManager(),storiesResponseList,storiesRepository);
binding.allStoriesListView.setAdapter(adapter);
}
#Override
public void onStoryFetched(boolean asc) {
scrollToTop = asc;
if (binding.swiperefresh != null && binding.swiperefresh.isRefreshing()) {
binding.swiperefresh.setRefreshing(false);
}
binding.fetchStoriesProgress.setVisibility(View.GONE);
}
#Override
public void onPause() {
super.onPause();
if(adapter!=null) {
StoriesViewHolder view = (StoriesViewHolder) binding.allStoriesListView.findViewHolderForAdapterPosition(adapter.getPosition());
if (view != null && view.adapter.player!=null) {
view.adapter.player.setPlayWhenReady(false);
}
}
}
#Override
public void onResume() {
super.onResume();
if(adapter!=null) {
StoriesViewHolder view = (StoriesViewHolder) binding.allStoriesListView.findViewHolderForAdapterPosition(adapter.getPosition());
if (view != null && view.adapter.player!=null) {
view.adapter.player.setPlayWhenReady(true);
}
}
}
#Override
public void onDestroy() {
//storiesRepository.deleteAllStoryAndStoryMedia();
if(adapter!=null) {
StoriesViewHolder view = (StoriesViewHolder) binding.allStoriesListView.findViewHolderForAdapterPosition(adapter.getPosition());
if (view != null && view.adapter.player!=null) {
view.adapter.releasePlayer();
}
}
storiesResponseList.clear();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
linearLayoutManager = null;
scrollToTop = false;
storiesViewModel = null;
super.onDestroy();
}
}
AllStoriesAdapter.java
public class AllStoriesAdapter extends RecyclerView.Adapter<StoriesViewHolder> {
private Context context;
private List<StoriesResponse> storiesResponseList;
private HomeActivity activity;
private FragmentManager fragmentManager;
private int position;
public AllStoriesAdapter(HomeActivity activity, Context context, FragmentManager manager, List<StoriesResponse> storiesResponseList, StoriesRepository storiesRepository) {
this.context = context;
this.storiesResponseList = storiesResponseList;
this.activity = activity;
this.fragmentManager = manager;
}
#NonNull
#Override
public StoriesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
StoriesItemLayoutBinding itemBinding = StoriesItemLayoutBinding.inflate(layoutInflater, parent, false);
return new StoriesViewHolder(itemBinding);
}
#Override
public void onBindViewHolder(#NonNull final StoriesViewHolder holder, final int position) {
holder.bind(storiesResponseList.get(position), this, fragmentManager, activity);
}
}
#Override
public int getItemCount() {
return storiesResponseList.size();
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
/*#Override
public void onViewDetachedFromWindow(#NonNull StoriesViewHolder holder) {
super.onViewDetachedFromWindow(holder);
holder.binding.moreOptions.setOnClickListener(null);
if(holder.adapter!=null) {
holder.adapter.releasePlayer();
}
}*/
#Override
public void onViewRecycled(StoriesViewHolder holder) {
super.onViewRecycled(holder);
if(holder.adapter!=null) {
holder.adapter.releasePlayer();
}
}
public StoriesResponse getLastItemInList() {
return storiesResponseList.get(storiesResponseList.size() - 1);
}
}
StoriesViewHolder.java
public class StoriesViewHolder extends RecyclerView.ViewHolder{
public StoriesItemLayoutBinding binding;
public int dotsCount;
//private StoriesMediaPagerAdapter adapter;
public StoriesMediaRecyclerViewAdapter adapter;
private ArrayList<ImageView> dots;
private Context context;
private List<StoriesMediaItems> storyItemsList = new ArrayList<>();
public StoriesViewHolder(StoriesItemLayoutBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(StoriesResponse response, AllStoriesAdapter adapter, FragmentManager manager, HomeActivity activity) {
binding.setStories(response);
binding.setAdapter(adapter);
binding.executePendingBindings();
context = activity;
setUpStoriesAttachmentPager(response.getList(),activity,manager);
}
private void setUpStoriesAttachmentPager(List<StoriesMediaItems> storyItems, HomeActivity activity,FragmentManager manager) {
this.storyItemsList = storyItems == null ? new ArrayList<>() : storyItems;
binding.storiesItemPager.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
adapter = new StoriesMediaRecyclerViewAdapter(activity, storyItemsList, false);
binding.storiesItemPager.setAdapter(adapter);
binding.storiesItemPager.setItemViewCacheSize(0);
SnapHelper snapHelper = new PagerSnapHelper();
binding.storiesItemPager.setOnFlingListener(null);
snapHelper.attachToRecyclerView(binding.storiesItemPager);
binding.dotsContainer.attachToRecyclerView(binding.storiesItemPager, snapHelper);
if (storyItemsList.size() == 1) {
binding.dotsContainer.setVisibility(View.GONE);
} else {
binding.dotsContainer.setVisibility(View.VISIBLE);
}
}
}
StoriesMediaRecyclerViewAdapter.java
public class StoriesMediaRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_IMAGE = 1, TYPE_VIDEO = 2;
private List<StoriesMediaItems> storiesMediaItemsList;
private Context context;
private String tag = "";
Boolean isFromComment = false;
private SimpleExoPlayer player;
private DefaultTrackSelector trackSelector;
private SimpleExoPlayerView simpleExoPlayerView;
private MediaSource mediaSource;
private DefaultExtractorsFactory extractorsFactory;
private DataSource.Factory mediaDataSourceFactory;
private int position = -1;
public StoriesMediaRecyclerViewAdapter(Context context, List<StoriesMediaItems> storiesMediaItemsList,Boolean isFromComment) {
this.context = context;
this.storiesMediaItemsList = storiesMediaItemsList;
this.tag = tag;
this.isFromComment = isFromComment;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
if (viewType == TYPE_IMAGE) {
StoriesImageViewBinding itemBinding = StoriesImageViewBinding.inflate(layoutInflater, parent, false);
return new ImageViewHolder(itemBinding);
} else {
StoriesVideoViewBinding itemBinding = StoriesVideoViewBinding.inflate(layoutInflater, parent, false);
return new VideoViewHolder(itemBinding);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
StoriesMediaItems storiesMediaItems = storiesMediaItemsList.get(position);
if (holder instanceof ImageViewHolder) {
ImageViewHolder imageHolder = (ImageViewHolder) holder;
Log.d("StoriesTelloImageViewHolder","ImageViewHolder");
setPosition(holder.getAdapterPosition());
imageHolder.storiesImageViewBinding.captionView.setText(storiesMediaItems.getCaption());
imageHolder.storiesImageViewBinding.storiesImage.setImageURI(storiesMediaItems.getSourceUrl());
imageHolder.storiesImageViewBinding.storiesImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
byte[] decodedString = Base64.decode(storiesMediaItems.getThumbImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable image = new BitmapDrawable(context.getResources(), decodedByte);
Glide.with(context)
.load(Uri.parse(storiesMediaItems.getSourceUrl()))
.apply(new RequestOptions().placeholder(image))
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageHolder.storiesImageViewBinding.storiesImage);
imageHolder.storiesImageViewBinding.storiesImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFromComment) {
Intent intent = new Intent(context, StoriesImageViewerActivity.class);
intent.putExtra("storiesMedia", storiesMediaItems);
context.startActivity(intent);
}
else{
Intent intent = new Intent(context, StoriesCommentsActivity.class);
intent.putExtra("storyId", storiesMediaItemsList.get(position).getStoriesId());
intent.putExtra("Tag", storiesMediaItemsList.get(position).getTAG());
intent.putExtra("storyposition", position);
context.startActivity(intent);
}
}
});
} else {
VideoViewHolder videoHolder = (VideoViewHolder) holder;
Log.d("StoriesTelloVideoViewHolder","VideoViewHolder");
byte[] decodedString = Base64.decode(storiesMediaItemsList.get(holder.getAdapterPosition()).getThumbImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable image = new BitmapDrawable(context.getResources(), decodedByte);
Glide.with(context)
.load(image)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(videoHolder.itemBinding.videoPlayerThumbnail);
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
StoriesImageViewBinding storiesImageViewBinding;
public ImageViewHolder(StoriesImageViewBinding binding) {
super(binding.getRoot());
this.storiesImageViewBinding = binding;
}
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
StoriesVideoViewBinding itemBinding;
public VideoViewHolder(StoriesVideoViewBinding binding) {
super(binding.getRoot());
this.itemBinding = binding;
}
}
#Override
public int getItemViewType(int position) {
StoriesMediaItems storiesMediaItems = storiesMediaItemsList.get(position);
if (storiesMediaItems.getType().equalsIgnoreCase("image")) {
return TYPE_IMAGE;
} else {
return TYPE_VIDEO;
}
}
#Override
public int getItemCount() {
return storiesMediaItemsList.size();
}
public void initializeExoPlayer() {
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
extractorsFactory = new DefaultExtractorsFactory();
mediaDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, "TelloTalkStoriesPlayer"), (TransferListener<? super DataSource>) bandwidthMeter);
}
public void releasePlayer() {
if (player != null) {
player.stop();
player.release();
player = null;
trackSelector = null;
}
}
public MediaSource buildMediaSource(Uri uri, VideoViewHolder holder) {
mediaSource = new ExtractorMediaSource(uri,
mediaDataSourceFactory, extractorsFactory, null, null);
player.setPlayWhenReady(true);
player.prepare(mediaSource);
holder.itemBinding.videoPlayerView.setPlayer(player);
return mediaSource;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
Log.d("StoriesTelloOnViewRecycled","onViewRecycled");
//releasePlayer();
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
Log.d("StoriesTelloOnAttachedToRecyclerView","onAttachedToRecyclerView");
}
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
Log.d("StoriesTelloOnDetachedFromRecyclerView","onDetachedFromRecyclerView");
//releasePlayer();
}
#Override
public void onViewAttachedToWindow(#NonNull RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
Log.d("StoriesTelloOnViewAttachedToWindow","onViewAttachedToWindow");
if(holder instanceof ImageViewHolder){
releasePlayer();
}
else if(holder instanceof VideoViewHolder){
releasePlayer();
VideoViewHolder videoHolder = (VideoViewHolder) holder;
initializeExoPlayer();
setPosition(holder.getAdapterPosition());
byte[] decodedString = Base64.decode(storiesMediaItemsList.get(holder.getAdapterPosition()).getThumbImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable image = new BitmapDrawable(context.getResources(), decodedByte);
Glide.with(context)
.load(image)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(videoHolder.itemBinding.videoPlayerThumbnail);
buildMediaSource(Uri.parse(storiesMediaItemsList.get(holder.getAdapterPosition()).getSourceUrl()), (VideoViewHolder) holder);
player.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
if(isLoading){
((VideoViewHolder) holder).itemBinding.videoPlayerProgressbar.setVisibility(View.VISIBLE);
}
else
{
((VideoViewHolder) holder).itemBinding.videoPlayerProgressbar.setVisibility(View.GONE);
}
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState)
{
case Player.STATE_BUFFERING:
((VideoViewHolder) holder).itemBinding.videoPlayerProgressbar.setVisibility(View.VISIBLE);
break;
case Player.STATE_ENDED:
((VideoViewHolder) holder).itemBinding.videoPlayerThumbnail.setVisibility(View.VISIBLE);
break;
case Player.STATE_IDLE:
//if (ivPlayPause != null) {
// ivPlayPause.setVisibility(View.VISIBLE);
//}
// if (player != null) {
// player.seekTo(0);
// player.setPlayWhenReady(true);
// }
//ivPlayPause.setImageResource(R.drawable.video_play);
//isPlay = false;
break;
case Player.STATE_READY:
((VideoViewHolder) holder).itemBinding.videoPlayerProgressbar.setVisibility(View.GONE);
((VideoViewHolder) holder).itemBinding.videoPlayerThumbnail.setVisibility(View.GONE);
//ivThumbnail.setVisibility(View.GONE);
//progressBar.setVisibility(View.GONE);
//handler.postDelayed(runnable, 1000);
break;
default:
break;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
}
#Override
public void onViewDetachedFromWindow(#NonNull RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
Log.d("StoriesTelloOnViewDetachedFromWindow","onViewDetachedFromWindow");
}
}

Pagination not working properly Android. It is showing all item at a time

I have recyclerview with 30 items in it. When i try to scroll pagination is not working. It is showing all items instead of refreshing. Below is my code.
public class InstitutesWithSearchActivity extends AppCompatActivity {
PaginationAdapter adapter;
private static final int PAGE_START = 1;
private boolean isLoading, isLastPage = false;
private int TOTAL_PAGES = 2;
int itemCount = 0;
private int currentPage = PAGE_START;
ApiInterface apiInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new PaginationAdapter(this);
layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new PaginationScrollListener(layoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
//mocking network delay for api
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadNextPage();
}
},2000);
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
//init service and load data
apiInterface = ApiClient.getClient().create(ApiInterface.class);
loadFirstPage();
}
private void loadNextPage() {
Call<InstituteResponseModel> call = apiInterface.masterInstitutes();
call.enqueue(new Callback<InstituteResponseModel>() {
#Override
public void onResponse(Call<InstituteResponseModel> call, Response<InstituteResponseModel> response) {
adapter.removeLoadingFooter();
isLoading = false;
ArrayList<InstituteModel> results = fetchResults(response);
adapter.addAll(results);
if (currentPage != PAGE_START) adapter.removeLoadingFooter();
adapter.addAll(results);
if (currentPage < TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
isLoading = false;
}
#Override
public void onFailure(Call<InstituteResponseModel> call, Throwable t) {
t.printStackTrace();
}
});
}
private void loadFirstPage() {
Log.e(TAG,"loadFirstPage");
Call<InstituteResponseModel> call = apiInterface.masterInstitutes();
call.enqueue(new Callback<InstituteResponseModel>() {
#Override
public void onResponse(Call<InstituteResponseModel> call, Response<InstituteResponseModel> response) {
ArrayList<InstituteModel> results = fetchResults(response);
progressBar.setVisibility(View.GONE);
adapter.addAll(results);
if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
}
#Override
public void onFailure(Call<InstituteResponseModel> call, Throwable t) {
t.printStackTrace();
}
});
}
private ArrayList<InstituteModel> fetchResults(Response<InstituteResponseModel> response) {
InstituteResponseModel responseModel = response.body();
return responseModel.getData();
}
}
I don't know what is the mistake from my side. I'm new to this pagination concept. I'm getting example code which uses forloop to show data. I'm using API to show data in Recyclerview.
public class PaginationAdapter extends RecyclerView.Adapter {
private static final int ITEM = 0;
private static final int LOADING = 1;
boolean isLoadingAdded = false;
private ArrayList<InstituteModel> modelArrayList;
Context context;
public PaginationAdapter(Context context) {
this.context = context;
modelArrayList = new ArrayList<>();
}
public ArrayList<InstituteModel> getInstitutes() {
return modelArrayList;
}
public void setInstitutes(ArrayList<InstituteModel> modelArrayList) {
this.modelArrayList = modelArrayList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType){
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater){
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.institute_row_layout, parent, false);
viewHolder = new InstituteHolder(v1);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int parent) {
InstituteModel model = modelArrayList.get(parent);
switch (getItemViewType(parent)){
case ITEM:
final InstituteHolder instituteHolder = (InstituteHolder) holder;
instituteHolder.instName.setText(model.getInstituteName());
Glide.with(context)
.load(model.getImageURL())
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
instituteHolder.progressBar.setVisibility(GONE);
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
instituteHolder.progressBar.setVisibility(GONE);
return false;
}
})
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.crossFade()
.into(instituteHolder.instImg);
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return modelArrayList == null ? 0 : modelArrayList.size();
}
#Override
public int getItemViewType(int position) {
return (position == modelArrayList.size()-1 && isLoadingAdded) ? LOADING : ITEM;
}
public void add(InstituteModel m){
modelArrayList.add(m);
notifyItemInserted(modelArrayList.size()-1);
}
public void addAll(ArrayList<InstituteModel> modelsList){
for (InstituteModel model : modelsList){
add(model);
}
}
public void remove(InstituteModel model){
int position = modelArrayList.indexOf(model);
if (position > -1){
modelArrayList.remove(position);
notifyItemRemoved(position);
}
}
public void clear(){
isLoadingAdded = false;
while (getItemCount()>0){
remove(getItem(0));
}
}
public boolean isEmpty(){
return getItemCount() == 0;
}
public void addLoadingFooter(){
isLoadingAdded = true;
add(new InstituteModel());
}
public void removeLoadingFooter(){
isLoadingAdded = false;
int position = modelArrayList.size() -1;
InstituteModel result = getItem(position);
if (result != null){
modelArrayList.remove(position);
notifyItemRemoved(position);
}
}
public InstituteModel getItem(int position){return modelArrayList.get(position);}
protected class InstituteHolder extends RecyclerView.ViewHolder {
TextView instName;
ImageView instImg;
TextView cityName, areaName;
RelativeLayout cardView;
ProgressBar progressBar;
public InstituteHolder(#NonNull View itemView) {
super(itemView);
instImg = itemView.findViewById(R.id.course_image);
instName = itemView.findViewById(R.id.course_name);
areaName = itemView.findViewById(R.id.course_area);
cityName = itemView.findViewById(R.id.course_city);
progressBar = itemView.findViewById(R.id.imgProgress);
cardView = itemView.findViewById(R.id.cardView);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(#NonNull View itemView) {
super(itemView);
}
}
}

How to sort a Recyclerview?

I am trying to sort the list of custom objects and display in Recyclerview. After displaying the items in recyclerview. I am sorting the list in the Activity and calling adapter.notifyDataSetChanged() but its not working.
Code in MainActivity.java:
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
Adapter code:
public class BeerListAdapter extends RecyclerView.Adapter<BeerListAdapter.MyViewHolder> {
private static ClickListener clickListener;
private Context context;
private LayoutInflater inflater;
private List<BeerData> beerDataList;
private List<BeerData> copyList;
public BeerListAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
beerDataList = new ArrayList<>();
copyList = new ArrayList<>();
}
public void setList(List<BeerData> beerDataList) {
if (this.beerDataList.isEmpty()) {
this.beerDataList.addAll(beerDataList);
copyList.addAll(beerDataList);
}
notifyDataSetChanged();
}
public void filter(String query) {
beerDataList.clear();
if (query.isEmpty()) {
beerDataList.addAll(copyList);
} else {
for (BeerData beerData : copyList) {
if (beerData.getName().replaceAll("[\\s]", "").toLowerCase().contains(query.replaceAll("[\\s]", "").toLowerCase())) {
beerDataList.add(beerData);
}
}
}
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_beer_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.beerName.setText(beerDataList.get(position).getName());
holder.styleName.setText(beerDataList.get(position).getStyle());
holder.alcoholContent.setText("Alcohol Content: " + beerDataList.get(position).getAbv());
holder.quantity.setText(beerDataList.get(position).getQuantity().toString());
}
#Override
public int getItemCount() {
return beerDataList.size();
}
public void setOnItemClickListener(ClickListener clickListener) {
BeerListAdapter.clickListener = clickListener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView beerName, alcoholContent, styleName, quantity;
ImageView add, minus;
MyViewHolder(View itemView) {
super(itemView);
beerName = itemView.findViewById(R.id.beerName);
alcoholContent = itemView.findViewById(R.id.alcoholContent);
styleName = itemView.findViewById(R.id.beerStyle);
quantity = itemView.findViewById(R.id.quantity);
add = itemView.findViewById(R.id.add);
minus = itemView.findViewById(R.id.minus);
add.setOnClickListener(this);
minus.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
clickListener.onAddClick(getAdapterPosition(), v);
break;
case R.id.minus:
clickListener.onMinusClick(getAdapterPosition(), v);
break;
}
}
}
public interface ClickListener {
void onAddClick(int position, View v);
void onMinusClick(int position, View v);
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, LoginResultCallBack {
private static final String TAG = MainActivity.class.getSimpleName();
#Inject
MyApplication application;
LoginViewModel loginViewModel;
#BindView(R.id.beerListRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.progressBar)
ProgressBar progressBar;
private BeerListAdapter adapter;
private List<BeerData> beerDataList;
private Menu menu;
private String sortType = "unsorted";
private Disposable networkDisposable;
List<BeerData> originalList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
((MyApplication) getApplication()).getComponent().inject(this);
loginViewModel = ViewModelProviders.of(this,new LoginViewModelFactory(application,this)).get(LoginViewModel.class);
adapter = new BeerListAdapter(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new BeerListAdapter.ClickListener() {
#Override
public void onAddClick(int position, View v) {
addItem(position);
}
#Override
public void onMinusClick(int position, View v) {
removeItem(position);
}
});
}
public void fetchData() {
progressBar.setVisibility(View.VISIBLE);
loginViewModel.fetchData();
loginViewModel.result.observe(this, new Observer<NetworkResponse>() {
#Override
public void onChanged(#Nullable NetworkResponse networkResponse) {
progressBar.setVisibility(View.GONE);
assert networkResponse != null;
if (networkResponse.getPostData() != null) {
beerDataList = new ArrayList<>();
originalList = networkResponse.getPostData();
beerDataList = networkResponse.getPostData();
Log.e(TAG, "Response: " + networkResponse.getPostData().get(0).getAbv());
progressBar.setVisibility(View.GONE);
adapter.setList(networkResponse.getPostData());
} else {
Log.e(TAG, "Response: " + networkResponse.getError().getLocalizedMessage());
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Beer");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cart:
Log.e(TAG, "cart clicked");
break;
case R.id.sort:
if (beerDataList != null) {
if (sortType.equalsIgnoreCase("unsorted")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "ascend";
menu.getItem(2).setTitle(R.string.unsorted);
} else if (sortType.equalsIgnoreCase("ascend")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o2.getAbv().compareToIgnoreCase(o1.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "descend";
menu.getItem(2).setTitle(R.string.view_original);
} else {
Log.e(TAG,beerDataList.size()+" Size");
beerDataList.clear();
beerDataList.addAll(originalList);
adapter.notifyDataSetChanged();
sortType = "unsorted";
menu.getItem(2).setTitle(R.string.sort);
}
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
#Override
protected void onResume() {
super.onResume();
networkDisposable = ReactiveNetwork.observeNetworkConnectivity(application)
.subscribeOn(Schedulers.io())
.filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
.filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Connectivity>() {
#Override
public void accept(final Connectivity connectivity) {
// do something
if (connectivity.isAvailable()) {
fetchData();
} else {
Toast.makeText(MainActivity.this, R.string.internet_issue, Toast.LENGTH_LONG).show();
}
}
});
}
private void addItem(int position) {
int quantity = beerDataList.get(position).getQuantity();
quantity++;
beerDataList.get(position).setQuantity(quantity);
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_full));
adapter.notifyDataSetChanged();
}
private void removeItem(int position) {
if (beerDataList.get(position).getQuantity() > 0) {
int quantity = beerDataList.get(position).getQuantity();
quantity--;
if (quantity == 0)
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_empty));
beerDataList.get(position).setQuantity(quantity);
adapter.notifyDataSetChanged();
}
}
private void safelyDispose(Disposable... disposables) {
for (Disposable subscription : disposables) {
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}
#Override protected void onPause() {
super.onPause();
safelyDispose(networkDisposable);
}
#Override
public void onSuccess(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void showProgress() {
}
#Override
public void hideProgress() {
}
}
What am I doing wrong here ?
You're not passing the sorted list to your adapter. You're just calling notifyDataSetChanged() which just tells the adapter that there is new data in its class and to use the baerDataList that is currently set within the class to refresh the list. Try this in your main activity.
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.setBeerDataList(beerDataList);
And setBeerDataList() in your adapter class.
private List<BeerData> beerDataList;
public void setBeerDataList(List<BeerData> sortedBeerDataList){
this.beerDataList = sortedBeerDataList;
notifyDataSetChanged();
}
Put sort function in MainActivity to BeerListAdapter:
private void sortBeer() {
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
notifyDataSetChanged();
}
then call adapter.sortBeer() when do sort action

Categories

Resources