Adapter Not showing all posts in RecyclerView - android

i am making app with Android Studio and fetching data in rest api using my Wordpress Website , i can see posts but the problem is it doesn’t display the very last 2 posts, when i log title in retrofit response in MainActivity i can see all posts, but in RecyclerView there is 2 posts hidden , this is my PostAdapter
private List<Model> dataset;
private Context mContext;
int total_types;
int viewTypeData = 0,viewTypeProgress = 2 ;
private static final int AD = 1;
private static final int LIST_AD_DELTA = 4;
AdView adview;
public PostAdapter(List<Model> list){
dataset = list;
}
#NotNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
mContext = parent.getContext();
if (viewType == AD) {
adview = new AdView(mContext);
adview.setAdSize( AdSize.LARGE_BANNER);
adview.setAdUnitId(mContext.getResources().getString(R.string.banner_ad_unit_id));
float density = mContext.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.LARGE_BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height);
adview.setLayoutParams(params);
new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("C5468C2B8941779E34B14EB796B9EA1B"));
AdRequest request = new AdRequest.Builder().build();
adview.loadAd(request);
return new Holder(adview);
}
if (viewType == viewTypeData){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list,parent,false);
return new MyDataHolder(view);
}else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading,parent,false);
return new MyProgressHolder(view);
}
}
public void clearApplications() {
int size = this.dataset.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
dataset.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(#NotNull RecyclerView.ViewHolder holder, int position) {
Model model = dataset.get(getRealPosition(position));
String tagID = model.tagsid;
if (holder instanceof MyDataHolder){
((MyDataHolder)holder).showModel(model);
Glide.with(mContext)
.load(model.imageUrl)
.dontAnimate()
.placeholder(R.drawable.icon)
.into( ((MyDataHolder)holder).imageView);
}
}
private int getRealPosition(int position) {
if (LIST_AD_DELTA == 0) {
return position;
} else {
return position - position / LIST_AD_DELTA;
}
}
#Override
public int getItemCount() {
return dataset.size();
}
#Override
public int getItemViewType(int position){
if (position > 0 && position % LIST_AD_DELTA == 0) {
return AD;
}
return viewTypeData;
}
void showHideProgress(boolean shouldShowProgress){
if (shouldShowProgress){
dataset.add(new Model("progress","","","","","","","","","",""));
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
notifyItemInserted(dataset.size()-1);
}
};
handler.post(r);
}else {
dataset.remove(dataset.size()-1);
notifyItemRemoved(dataset.size()-1);
}
}
void addItemsToList(List<Model> newItems){
if (dataset.isEmpty()){
dataset.addAll(newItems);
notifyDataSetChanged();
}else {
int lastItemPosition = dataset.size() -1;
dataset.addAll(newItems);
notifyItemRangeInserted(lastItemPosition,newItems.size());
}
}
class MyDataHolder extends RecyclerView.ViewHolder{
TextView titleView,subTitleView,postViews,tagsView,date;
ImageView imageView;
ImageButton sharebtn;
CardView rootView;
// Use Glide to load image to image view
public MyDataHolder(#NotNull View itemView) {
super(itemView);
titleView = itemView.findViewById(R.id.title);
date = itemView.findViewById(R.id.date);
subTitleView = itemView.findViewById(R.id.subtitle);
postViews = itemView.findViewById(R.id.postview);
tagsView = itemView.findViewById(R.id.tags);
imageView = itemView.findViewById(R.id.Icon);
sharebtn = itemView.findViewById(R.id.share);
rootView = itemView.findViewById(R.id.recycler_item_root_view);
rootView.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putParcelable("my_key",dataset.get(getRealPosition(getAdapterPosition())));
Intent intent = new Intent(mContext, PostDetails.class);
intent.putExtra("my_bundle",bundle);
mContext.startActivity(intent);
});
}
void showModel(Model model){
titleView.setText(model.title);
tagsView.setText(model.tags);
date.setText(model.date);
subTitleView.setText(model.subTitle);
postViews.setText(model.commentcount);
}
}
static class MyProgressHolder extends RecyclerView.ViewHolder{
ProgressBar progressBar;
public MyProgressHolder(#NotNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressbar);
}
void show(){
progressBar.setVisibility(View.VISIBLE);
}
}
public class Holder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public Holder(View itemView) {
super(itemView);
}
}
}
i have tried to remove Admob ads but still the same , please help

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);
}
}
}

RecyclerView won't load data retrieved from Firestore into ItemView

So, basically what I am trying to do is to show a bunch of Post type objects on my Android app's feed (HomeFragment). The posts are being successfully retrieved from Firestore (I did check the debugger) but somehow, not all of them get loaded in the recyclerView. The itemViewHolder is only loaded with how I defined it as an XML, fields filled with lore Ipsum.
This would be my code:
HomeFragment:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private boolean isLoading = false;
private ArrayList<String> rowsArrayList = new ArrayList<>();
public static ArrayList<Post> appliedToList = new ArrayList<>();
private User currentUser = new User();
private View root;
private TextView userState;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
setState();
appliedToPostsRetrieverFromHomePage(getContext());
checkForPostFragment();
recyclerView = root.findViewById(R.id.recyclerView);
initAdapter();
initScrollListener();
return root;
}
private void initAdapter() {
recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), 2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(recyclerViewAdapter);
}
private void initScrollListener() {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (!isLoading) {
if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) {
//bottom of list!
loadMore();
isLoading = true;
}
}
}
});
}
private void loadMore() {
rowsArrayList.add(null);
recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
rowsArrayList.remove(rowsArrayList.size() - 1);
int scrollPosition = rowsArrayList.size();
recyclerViewAdapter.notifyItemRemoved(scrollPosition);
int currentSize = scrollPosition;
int nextLimit = currentSize + 10;
while (currentSize - 1 < nextLimit) {
rowsArrayList.add("Item " + currentSize);
currentSize++;
}
recyclerViewAdapter.notifyDataSetChanged();
isLoading = false;
}
}, 2000);
}
#Override
public void onAttachFragment(#NonNull Fragment fragment) {
super.onAttachFragment(fragment);
}
RecyclerViewAdapter:
All view types represent kind of the same layout, the only difference between them is what is wrote on a certain button. Remember, some of the posts are successfully loaded!
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_APPLY = 0;
private final int VIEW_TYPE_MORE = 1;
private final int VIEW_TYPE_BEGIN = 2;
private final int VIEW_TYPE_PENDING = 3;
private final int VIEW_TYPE_END = 4;
private final int VIEW_TYPE_ON_GOING = 5;
private final int VIEW_TYPE_LOADING = 6;
private ArrayList<Post> list = new ArrayList();
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
private Context context;
private User currentUser;
private int recyclerType;
static ArrayList<User> applicantsList = new ArrayList<>();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
public RecyclerViewAdapter(Context context, int recyclerType) {
this.context = context;
this.recyclerType = recyclerType;
if (recyclerType == 0) {
myPostsRetriever(context);
} else if (recyclerType == 1) {
appliedToPostsRetriever(context);
} else if (recyclerType == 2) {
homePostsRetriever(context);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_APPLY) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_apply, parent, false);
return new ItemViewHolder(view);
} else if (viewType == VIEW_TYPE_MORE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_more, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_BEGIN) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_begin, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_PENDING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_pending, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_END) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_end, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_ON_GOING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_on_going, parent, false);
return new LoadingViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
return new LoadingViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
populateItemRows((ItemViewHolder) viewHolder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
showLoadingView((LoadingViewHolder) viewHolder, position);
}
}
#Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
#Override
public int getItemViewType(int position) {
if (list.get(position) != null) {
if (!list.get(position).getOwner().equals(userId) &&
!checkIfAlreadyAppliedToPost(position) &&
list.get(position).getMinNeededPersons() >= list.get(position).getApplicants()) {
return VIEW_TYPE_APPLY;
} else if (recyclerType == 1) {
return VIEW_TYPE_MORE;
} else if (list.get(position).getOwner().equals(userId) && timeCheck(list.get(position))) {
return VIEW_TYPE_BEGIN;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)
|| !list.get(position).getOwner().equals(userId) && checkIfAlreadyAppliedToPost(position) && !checkIfStarted(position)) {
return VIEW_TYPE_PENDING;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)) {
return VIEW_TYPE_END;
} else if (!list.get(position).getOwner().equals(userId) && checkIfStarted(position)){
return VIEW_TYPE_ON_GOING;
}else if (list.get(position).getOwner().equals(userId))
return VIEW_TYPE_MORE;
}
return VIEW_TYPE_LOADING;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView description;
TextView location;
TextView minNeededPersons;
TextView maxNeededPersons;
TextView reward;
TextView time;
CheckBox physical;
Button button;
ItemViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.postTitle);
description = itemView.findViewById(R.id.postDescription);
location = itemView.findViewById(R.id.postLocationText);
time = itemView.findViewById((R.id.postDateAndTime));
minNeededPersons = itemView.findViewById(R.id.people);
maxNeededPersons = itemView.findViewById(R.id.people);
reward = itemView.findViewById(R.id.reward);
physical = itemView.findViewById(R.id.checkBox2);
button = itemView.findViewById(R.id.applyButton);
}
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
private void showLoadingView(LoadingViewHolder viewHolder, int position) {
}
private void populateItemRows(ItemViewHolder viewHolder, int position) {
Post item = list.get(position);
viewHolder.title.setText(item.getTheTitle());
viewHolder.description.setText(item.getDescription());
viewHolder.location.setText(item.getLocation());
viewHolder.location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showLocation = new Intent(context, MapsActivity.class);
context.startActivity(showLocation);
}
});
viewHolder.minNeededPersons.setText(String.valueOf(item.getMinNeededPersons()));
viewHolder.maxNeededPersons.setText(String.valueOf(item.getMaxPersonsNeeded()));
viewHolder.reward.setText(String.valueOf(item.getReward()));
viewHolder.physical.setChecked(item.isPhysical());
Date timeAndDate = item.getTime().toDate();
viewHolder.time.setText(new SimpleDateFormat("HH:mm dd.MM.yyyy").format(timeAndDate));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if (viewHolder.button.getText().equals(context.getResources().getString(R.string.apply))) {
onApplyTapped(position);
viewHolder.button.setText(R.string.pending);
viewHolder.button.setBackgroundColor(Color.parseColor("#F2CF59"));
viewHolder.button.setClickable(false);
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.begin_job))) {
onBeginTapped(position);
viewHolder.button.setText(R.string.end_job);
viewHolder.button.setBackgroundColor(Color.parseColor("#F8CA9D"));
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.end_job))) {
onEndTapped(position);
viewHolder.button.setBackgroundColor(Color.parseColor("#FB8E7E"));
viewHolder.button.setClickable(false);
viewHolder.button.setText(R.string.finished);
}
}
});
viewHolder.itemView.findViewById(R.id.seePostButton).setOnClickListener(new View.OnClickListener()
{ not relevant }
private void homePostsRetriever(Context context) {
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collectionGroup("posts").limit(10).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) {
Post post = new Post();
post.setAvailability(documentSnapshot.getBoolean("available"));
post.setTitle(documentSnapshot.getString("title"));
post.setDescription(documentSnapshot.getString("description"));
post.setLocation(documentSnapshot.getString("location"));
post.setApplicants(documentSnapshot.getLong("applicants").intValue());
post.setOwner(documentSnapshot.getString("owner"));
post.setMinNeededPersons(documentSnapshot.getLong("minNrOfPeople").intValue());
post.setMaxPersonsNeeded(documentSnapshot.getLong("maxNrOfPeople").intValue());
post.setReward(Objects.requireNonNull(documentSnapshot.getLong("reward")).floatValue());
post.setPhysical(documentSnapshot.getBoolean("physicalExcertion"));
post.setTime(documentSnapshot.getTimestamp("time"));
post.setId(documentSnapshot.getId());
post.setStarted(documentSnapshot.getBoolean("started"));
list.add(post);
}
notifyDataSetChanged();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "No document found", Toast.LENGTH_SHORT).show();
}
});
}
I don't think you are calling bind methods correctly, try:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
ItemViewHolder holder = (ItemViewHolder)viewHolder;
holder.populateItemRows(holder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
LoadingViewHolder holder = (LoadingViewHolder)viewHolder;
holder.showLoadingView(holder , position);
}
}
Also this method:
private void populateItemRows(ItemViewHolder viewHolder, int position) {
.....
....
....
}
Is not found in your ItemViewHolder class

Dynamic header in grid view android

i want to sort my photos according to date and display them in a grid layout using grid layout manager in recycler view like attached picture but i dont know how to do this.i want this type of view after sorting
i added header but at fix index ,dynamically how to do this ?because when we don't know how many photos are there in a specific date so it is not possible to add header in photos list at that specific index.
MyPhotoListAdapter.java
public class MYPhotoListAdapter extends RecyclerView.Adapter {
private List<PhotoInfo> mSelectList;
private List<PhotoInfo> list;
private int mScreenWidth;
private int mRowWidth;
private Activity mActivity;
private List generalList;
public final int HEADER_TYPE=1;
public final int OTHER_TYPE=2;
public MYPhotoListAdapter(Activity activity, List<PhotoInfo> list, List<PhotoInfo> selectList, int screenWidth) {
this.mSelectList = selectList;
this.mScreenWidth = screenWidth;
this.mRowWidth = mScreenWidth / 3;
this.list=list;
this.mActivity = activity;
generalList=list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case HEADER_TYPE:
View headerview = LayoutInflater.from(parent.getContext()).inflate(R.layout.textheader_layout,null);
return new textViewHolder(headerview);
default:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gf_adapter_photo_list_item,null);
setHeight(view);
return new viewHolder(view);
}
}
private void setHeight(final View convertView) {
int height = mScreenWidth / 3 - 8;
convertView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(position==0){
return;
}
PhotoInfo photoInfo = (PhotoInfo) generalList.get(position);
String path = "";
if (photoInfo != null) {
path = photoInfo.getPhotoPath();
}
((viewHolder)holder).mIvThumb.setImageResource(R.drawable.ic_gf_default_photo);
Drawable defaultDrawable = mActivity.getResources().getDrawable(R.drawable.ic_gf_default_photo);
GalleryFinal.getCoreConfig().getImageLoader().displayImage(mActivity, path, ((viewHolder)holder).mIvThumb, defaultDrawable, mRowWidth, mRowWidth);
((viewHolder)holder).mView.setAnimation(null);
if (GalleryFinal.getCoreConfig().getAnimation() > 0) {
((viewHolder)holder).mView.setAnimation(AnimationUtils.loadAnimation(mActivity, GalleryFinal.getCoreConfig().getAnimation()));
}
((viewHolder)holder).mIvCheck.setImageResource(R.drawable.ic_check_image);
if (GalleryFinal.getFunctionConfig().isMutiSelect()) {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
if (mSelectList.contains(photoInfo)) {
((viewHolder)holder).mIvCheck.setVisibility(View.VISIBLE);
// holder.mIvCheck.setBackgroundColor(GalleryFinal.getGalleryTheme().getCheckSelectedColor());
} else {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
// holder.mIvCheck.setBackgroundColor(GalleryFinal.getGalleryTheme().getCheckNornalColor());
}
} else {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return generalList.size();
}
#Override
public int getItemViewType(int position) {
return position==0?HEADER_TYPE:OTHER_TYPE;
}
public class viewHolder extends RecyclerView.ViewHolder{
public GFImageView mIvThumb;
public ImageView mIvCheck;
View mView;
public viewHolder(View itemView) {
super(itemView);
mView = itemView;
mIvThumb = (GFImageView) itemView.findViewById(R.id.iv_thumb);
mIvCheck = (ImageView) itemView.findViewById(R.id.iv_check);
}
}
public class textViewHolder extends RecyclerView.ViewHolder{
TextView textView;
public textViewHolder(View itemView) {
super(itemView);
textView=new TextView(itemView.getContext());
}
}
}
Activity.java
final GridLayoutManager glm=new GridLayoutManager(this,5);
mGvPhotoList.setLayoutManager(glm);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return position==0?glm.getSpanCount():1;
}
});
myPhotoListAdapter=new MYPhotoListAdapter(this, mCurPhotoList, mSelectPhotoList, mScreenWidth);
mGvPhotoList.setAdapter(myPhotoListAdapter);
this code is working but here i'm adding header on fixed index but i wan't it dynamically for each specific date .
PhotoInfo.java
public class PhotoInfo implements Serializable {
private int photoId;
private String photoPath;
//private String thumbPath;
private int width;
private int height;
private String photoDate;
public PhotoInfo() {
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
public int getPhotoId() {
return photoId;
}
public void setPhotoId(int photoId) {
this.photoId = photoId;
}
//
//public String getThumbPath() {
// return thumbPath;
//}
//
//public void setThumbPath(String thumbPath) {
// this.thumbPath = thumbPath;
//}
public String getPhotoDate() {
return photoDate;
}
public void setPhotoDate(String photoDate) {
this.photoDate = photoDate;
}
#Override
public boolean equals(Object o) {
if (o == null || !(o instanceof PhotoInfo)) {
return false;
}
PhotoInfo info = (PhotoInfo) o;
if (info == null) {
return false;
}
return TextUtils.equals(info.getPhotoPath(), getPhotoPath());
}
}

delay in downloading image from server with volley

I try to downloading image from server with volley and show them in recyclerview.
it is work correctly but the downloading image is very low.
(the size of each image approximately 50 kb).
what can i do?
is there better and optimize code than it?
this is my helper class:
public class StartActivity {
// for recyclerView - downLoad Data
private static final int LIMIT = 6;
OnLoadMoreListener onLoadMoreListener;
int idImage = 1;
private List<StructUser> structList = new ArrayList<>();
private AdapterUser adapter;
private int CURRENT_ITEM = 1;
private Context context;
private String TAG = StartActivity.class.getSimpleName();
//----------------------------------------------------
public StartActivity(Context context) {
this.context = context;
}
public void getDataAndSetInRecyclerView(RecyclerView recyclerView) {
loadData(CURRENT_ITEM);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new AdapterUser(recyclerView, structList, context);
onLoadMoreListener = new OnLoadMoreListener() {
#Override
public void onLoadMore() {
structList.add(null);
adapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
structList.remove(structList.size() - 1);
// adapter.notifyItemRemoved(structList.size());
loadData(CURRENT_ITEM);
}
}, 2000);
}
};
adapter.setOnLoadMoreListener(onLoadMoreListener);
recyclerView.setAdapter(adapter);
}
private void loadData(final int CURRENT_ITEM) {
String url = Config.DATA_URL + CURRENT_ITEM;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ActivityMain.hideProgressBar();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
StructUser structUser = new StructUser();
if (!jsonObject.isNull(Config.TAG_TITLE))
structUser.setNetworkImageView(jsonObject.getString(Config.TAG_TITLE));
if (!jsonObject.isNull(Config.TAG_IMAGE_URL)) {
structUser.setNetworkImageView(Config.IMG_SERVER + idImage + ".png");
idImage++;
}
structList.add(structUser);
}
adapter.notifyDataSetChanged();
adapter.setLoaded();
// not show progressBar at end of list when get all data
if (response.toString().contains("[]")) {
adapter.reachEndList();
Toast.makeText(context, "not More Data to Show", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// hide progressBar
ActivityMain.hideProgressBar();
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest, TAG);
this.CURRENT_ITEM = this.CURRENT_ITEM + LIMIT;
}
}
this is my adapter:
public class AdapterUser extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
public int visibleThreshold = 2;
boolean isLoading;
private int lastVisibleItem, totalItemCount;
private List<StructUser> structList = new ArrayList<>();
private OnLoadMoreListener mOnLoadMoreListener;
private Context context;
// load image from server -------------------------------------------------
private static ImageLoader imageLoader = ImageLoader.getInstance();
public static DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_cloud_download)
.showImageForEmptyUri(R.mipmap.ic_picture)
.showImageOnFail(android.R.drawable.ic_dialog_alert)
.cacheInMemory(true)
.cacheOnDisk(false)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
//---------------------------------------------------------------
public AdapterUser(RecyclerView mRecyclerView, List<StructUser> structList, Context context) {
this.context = context;
this.structList = structList;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= visibleThreshold + (lastVisibleItem)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setLoaded() {
isLoading = false;
}
public void reachEndList() {
isLoading = true;
}
//========================================================
#Override
public int getItemViewType(int position) {
return structList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_start_activity , viewGroup, false);
return new UserViewHolder(view);
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
UserViewHolder userViewHolder = (UserViewHolder) holder;
StructUser user = structList.get(position);
userViewHolder.title.setText(user.getTitle());
// load image from server
imageLoader.displayImage(user.getNetworkImageView(), userViewHolder.networkImageView, options);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return structList == null ? 0 : structList.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
class UserViewHolder extends RecyclerView.ViewHolder {
public TextView title;
// for download & cash image
public ImageView networkImageView;
public UserViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txtTitle);
networkImageView = (ImageView) itemView.findViewById(R.id.networkImageView);
}
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
}
Use Glide for downloading Image...
Glide.with(ActivityName.this)
.load(image_url)
.into(imageView_object);
It will download image and set in ImageView.

i am trying to set a header to staggardGridLayoutManeger

i am trying to set a header to staggardGridLayoutManeger i have the code from this url https://github.com/willblaschko/header-footer-recycler-view. this code contains header and footer for all the types of layout. can anyone help to set the adapter only for staggardGridLayout this is the code form the sample at
enter code here
public class RecyclerViewHeaderFooterAdapter extends RecyclerView.Adapter {
public static final int TYPE_MANAGER_OTHER = 0;
public static final int TYPE_MANAGER_LINEAR = 1;
public static final int TYPE_MANAGER_GRID = 2;
public static final int TYPE_MANAGER_STAGGERED_GRID = 3;
public static final int TYPE_HEADER = 7898;
public static final int TYPE_FOOTER = 7899;
private List<View> mHeaders = new ArrayList<>();
private List<View> mFooters = new ArrayList<>();
private int mManagerType;
private RecyclerView.LayoutManager mManager;
private IRecyclerViewIntermediary mIntermediary;
public RecyclerViewHeaderFooterAdapter(RecyclerView.LayoutManager manager, IRecyclerViewIntermediary intermediary){
setManager(manager);
this.mIntermediary = intermediary;
}
public void setLayoutManager(RecyclerView.LayoutManager manager){
setManager(manager);
}
private void setManager(RecyclerView.LayoutManager manager){
mManager = manager;
if(mManager instanceof GridLayoutManager){
mManagerType = TYPE_MANAGER_GRID;
((GridLayoutManager) mManager).setSpanSizeLookup(mSpanSizeLookup);
}else if(mManager instanceof LinearLayoutManager){
mManagerType = TYPE_MANAGER_LINEAR;
}else if(mManager instanceof StaggeredGridLayoutManager){
mManagerType = TYPE_MANAGER_STAGGERED_GRID;
((StaggeredGridLayoutManager) mManager).setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
}else{
mManagerType = TYPE_MANAGER_OTHER;
}
}
public int getManagerType(){
return mManagerType;
}
public int getGridSpan(int position){
if(isHeader(position) || isFooter(position)){
return getSpan();
}
position -= mHeaders.size();
if(mIntermediary.getItem(position) instanceof IGridItem){
return ((IGridItem) mIntermediary.getItem(position)).getGridSpan();
}
return 1;
}
private int getSpan(){
if(mManager instanceof GridLayoutManager){
return ((GridLayoutManager) mManager).getSpanCount();
}else if(mManager instanceof StaggeredGridLayoutManager){
return ((StaggeredGridLayoutManager) mManager).getSpanCount();
}
return 1;
}
private GridLayoutManager.SpanSizeLookup mSpanSizeLookup = new GridLayoutManager.SpanSizeLookup(){
#Override
public int getSpanSize(int position) {
return getGridSpan(position);
}
};
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
//if our position is one of our items (this comes from getItemViewType(int position) below)
if(type != TYPE_HEADER && type != TYPE_FOOTER) {
return mIntermediary.getViewHolder(viewGroup, type);
//else we have a header/footer
}else{
//create a new framelayout, or inflate from a resource
FrameLayout frameLayout = new FrameLayout(viewGroup.getContext());
//make sure it fills the space
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return new HeaderFooterViewHolder(frameLayout);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder vh, int position) {
//check what type of view our position is
if(isHeader(position)){
View v = mHeaders.get(position);
//add our view to a header view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
}else if(isFooter(position)){
View v = mFooters.get(position-mIntermediary.getItemCount()-mHeaders.size());
//add our view to a footer view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
}else {
//it's one of our items, display as required
mIntermediary.populateViewHolder(vh, position-mHeaders.size());
}
}
private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view){
//if it's a staggered grid, span the whole layout
if(mManagerType == TYPE_MANAGER_STAGGERED_GRID){
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.setFullSpan(true);
vh.itemView.setLayoutParams(layoutParams);
}
//if the view already belongs to another layout, remove it
if(view.getParent() != null){
((ViewGroup)view.getParent()).removeView(view);
}
//empty out our FrameLayout and replace with our header/footer
vh.base.removeAllViews();
vh.base.addView(view);
}
private boolean isHeader(int position){
return(position < mHeaders.size());
}
private boolean isFooter(int position){
return(position >= mHeaders.size() + mIntermediary.getItemCount());
}
#Override
public int getItemCount() {
return mHeaders.size() + mIntermediary.getItemCount() + mFooters.size();
}
#Override
public int getItemViewType(int position) {
//check what type our position is, based on the assumption that the order is headers > items > footers
if(isHeader(position)){
return TYPE_HEADER;
}else if(isFooter(position)){
return TYPE_FOOTER;
}
int type = mIntermediary.getItemViewType(position);
if(type == TYPE_HEADER || type == TYPE_FOOTER){
throw new IllegalArgumentException("Item type cannot equal "+TYPE_HEADER+" or "+TYPE_FOOTER);
}
return type;
}
//add a header to the adapter
public void addHeader(View header){
if(!mHeaders.contains(header)){
mHeaders.add(header);
//animate
notifyItemInserted(mHeaders.size()-1);
}
}
//remove a header from the adapter
public void removeHeader(View header){
if(mHeaders.contains(header)){
//animate
notifyItemRemoved(mHeaders.indexOf(header));
mHeaders.remove(header);
}
}
//add a footer to the adapter
public void addFooter(View footer){
if(!mFooters.contains(footer)){
mFooters.add(footer);
//animate
notifyItemInserted(mHeaders.size()+mIntermediary.getItemCount()+mFooters.size()-1);
}
}
//remove a footer from the adapter
public void removeFooter(View footer){
if(mFooters.contains(footer)) {
//animate
notifyItemRemoved(mHeaders.size()+mIntermediary.getItemCount()+mFooters.indexOf(footer));
mFooters.remove(footer);
}
}
//our header/footer RecyclerView.ViewHolder is just a FrameLayout
public static class HeaderFooterViewHolder extends RecyclerView.ViewHolder{
FrameLayout base;
public HeaderFooterViewHolder(View itemView) {
super(itemView);
base = (FrameLayout) itemView;
}
}
}
I solved this problem adding a new type to my adapter for the header. Look at this example: https://stackoverflow.com/a/26573338/1949163.
After that, to make the header span all columns I created a new LayoutParams and set full span to true in the adapter implementation:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CommonItemViewHolder) {
...
} else if (holder instanceof HeaderViewHolder) {
...
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.setFullSpan(true);
holder.itemView.setLayoutParams(layoutParams);
}
}

Categories

Resources