Images are not showing after implementing Pagination in my RecyclerView - android

I have implemented Pagination in my RecyclerView but after implementing pagination the images are not showing up
Ok I have implemented this pagination answer
Ok because the answer above is for LinearLayoutManager and I'm using StaggeredGridLayoutManager I have done some modifications in the addOnScrollListener
I have only included the necessary code of Home_Fragment.java so it doesn't get confusing
and long but if you want more references to the code please tell me I
will update the question
Home_Fragment.java
private int previousTotal = 0;
private final int visibleThreshold = 5;
private RecyclerView postRecyclerView;
private boolean loading = true;
private int firstVisibleItem, visibleItemCount, totalItemCount;
#SuppressLint("SourceLockedOrientationActivity")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
postRecyclerView.setLayoutManager(
staggeredGridLayoutManager
);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = staggeredGridLayoutManager.getChildCount();
totalItemCount = staggeredGridLayoutManager.getItemCount();
int[] firstVisibleItems = null;
firstVisibleItems = staggeredGridLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
getData();
loading = true;
}
}
});
return view;
}
private void getData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
postRecyclerView.setVisibility(View.VISIBLE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
assert upload != null;
upload.setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
postsAdapter.setUploads(mUploads);
//notify the adapter
postsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
PostAdapter_Home.java
public class PostAdapter_Home extends RecyclerView.Adapter<PostAdapter_Home.PostViewHolder> {
public static List<Upload> mUploads;
public Context mcontext;
public PostAdapter_Home(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(mcontext).inflate(R.layout.ex_home, parent, false);
return new PostViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setBaseColor(Color.parseColor("#F3F3F3"))
.setBaseAlpha(1)
.setHighlightColor(Color.parseColor("#E7E7E7"))
.setHighlightAlpha(1)
.setDropoff(50)
.build();
ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
shimmerDrawable.setShimmer(shimmer);
Upload uploadCurrent = mUploads.get(position);
Glide.with(mcontext)
.load(uploadCurrent.getmImageUrl())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(shimmerDrawable)
.centerCrop()
.fitCenter()
.into(holder.imageView);
// holder.imageView.setOnClickListener(view -> changeScaleType(holder, position));
}
#Override
public int getItemCount() {
return mUploads.size();
}
public void setUploads(List<Upload> uploads){
mUploads=uploads;
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
private final ShapeableImageView imageView;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagePostHome);
}
}
}
Update // Added Upload.java file as requested
Upload.java
package com.example.myappnotfinal.AdaptersAndMore;
import com.google.firebase.database.Exclude;
public class Upload {
private String mImageUrl;
private String mKey;
private String mUserName;
private String mComment;
public Upload() {
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmUserName() {
return mUserName;
}
public void setmUserName(String mUserName) {
this.mUserName = mUserName;
}
public String getmComment() {
return mComment;
}
public void setmComment(String mComment) {
this.mComment = mComment;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
#Exclude
public String getmKey() {
return mKey;
}
#Exclude
public void setmKey(String Key) {
this.mKey = Key;
}
}

Related

How to send pagination requests to firebase for endlessly scrollable recyclerview

I'm trying to include pagination in my app what I want that for eg in my firebase I have 500 images that are to be shown in the recycler view what I want is first 10 or 15 images are loaded in the recycler view at the beginning and when the user reaches to the end of the last item(image) it loads next 10 images (just like Instagram or facebook )
Note:- if anyone wants more reference of my code please tell me I will
update my question
Here is my code
Home_Fragment.java
private boolean loading = true;
private int pastVisibleItems, visibleItemCount, totalItemCount;
#SuppressLint("SourceLockedOrientationActivity")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
MaterialToolbar materialToolbar = view.findViewById(R.id.toolbar);
materialToolbar.setOnMenuItemClickListener(toolbarItemClickListener);
postRecyclerView = view.findViewById(R.id.recyclerViewHome);
shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
// this is for one item per scroll
// SnapHelper snapHelper = new PagerSnapHelper();
// snapHelper.attachToRecyclerView(verticalRecyclerView);
postRecyclerView.setAdapter(postsAdapter);
// listState = savedInstanceState.getParcelable("ListState");
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
postRecyclerView.setLayoutManager(
staggeredGridLayoutManager
);
getData();
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = staggeredGridLayoutManager.getChildCount();
totalItemCount = staggeredGridLayoutManager.getItemCount();
int[] firstVisibleItems = null;
firstVisibleItems = staggeredGridLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);
if (firstVisibleItems != null && firstVisibleItems.length > 0) {
pastVisibleItems = firstVisibleItems[0];
}
if (loading) {
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
loading = false;
getData();
Log.d("tag", "LOAD NEXT ITEM");
}
}
}
});
// setupFirebaseAuth();
shimmerFrameLayout.startShimmer();
mUploads = new ArrayList<>();
postsAdapter = new PostAdapter_Home(getContext(), mUploads);
postRecyclerView.setAdapter(postsAdapter);
postRecyclerView.scrollToPosition(Home_Fragment.saved_position);
return view;
}
private void getData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
postRecyclerView.setVisibility(View.VISIBLE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
assert upload != null;
upload.setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
postsAdapter.setUploads(mUploads);
//notify the adapter
postsAdapter.notifyDataSetChanged();
loading = true;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
loading = true;
}
});
}
PostAdapter_Home.java // Adapter Class
public class PostAdapter_Home extends RecyclerView.Adapter<PostAdapter_Home.PostViewHolder> {
public static List<Upload> mUploads;
public Context mcontext;
public PostAdapter_Home(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(mcontext).inflate(R.layout.ex_home, parent, false);
return new PostViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setBaseColor(Color.parseColor("#F3F3F3"))
.setBaseAlpha(1)
.setHighlightColor(Color.parseColor("#E7E7E7"))
.setHighlightAlpha(1)
.setDropoff(50)
.build();
ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
shimmerDrawable.setShimmer(shimmer);
Upload uploadCurrent = mUploads.get(position);
Glide.with(mcontext)
.load(uploadCurrent.getmImageUrl())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(shimmerDrawable)
.centerCrop()
.fitCenter()
.into(holder.imageView);
// holder.imageView.setOnClickListener(view -> changeScaleType(holder, position));
}
#Override
public int getItemCount() {
return mUploads.size();
}
public void setUploads(List<Upload> uploads){
mUploads=uploads;
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
private final ShapeableImageView imageView;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagePostHome);
}
}
}
Update // Added Upload.java file code as requested in the comment section
Upload.java
package com.example.myappnotfinal.AdaptersAndMore;
import com.google.firebase.database.Exclude;
public class Upload {
private String mImageUrl;
private String mKey;
private String mUserName;
private String mComment;
public Upload() {
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmUserName() {
return mUserName;
}
public void setmUserName(String mUserName) {
this.mUserName = mUserName;
}
public String getmComment() {
return mComment;
}
public void setmComment(String mComment) {
this.mComment = mComment;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
#Exclude
public String getmKey() {
return mKey;
}
#Exclude
public void setmKey(String Key) {
this.mKey = Key;
}
}
First you should separate fetching data logic from UI. Then your scroll controller (RecyclerView) should control which images should be called to download (so when it's loaded it should ask for first batch of images, when scroll happens - ask for another batch, etc.). And downloading and caching images is not a trivial task, that's why we have Glide and Coil in Android world.
As a side note please take a look at https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data and https://developer.android.com/topic/libraries/architecture/paging.
Please check what you're adding to the list of mUploads because every time you add items, you clear the list upfront mUploads.clear(); which may be not what you wanted.
Some notes:
dont make it static public static List<Upload> mUploads;
don't need to store mcontext, Context is already there
strip the problem out of unncessary stuff (e.g. drop shimmer, fix the problem, add shimmer when fixed)
Here what you need to do is setLimit for pagination process.
Here is and example:
private void getUsers(String nodeId) {
Query query;
if (nodeId == null)
query = FirebaseDatabase.getInstance().getReference()
.child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
.orderByKey()
.limitToFirst(mPostsPerPage);
else
query = FirebaseDatabase.getInstance().getReference()
.child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
.orderByKey()
.startAt(nodeId)
.limitToFirst(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel user;
List<UserModel> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
userModels.add(userSnapshot.getValue(UserModel.class));
}
mAdapter.addAll(userModels);
mIsLoading = false;
}
#Override
public void onCancelled(DatabaseError databaseError) {
mIsLoading = false;
}
});
}
So here you need to send last node id each time to get new list. After getting response just add your data to ArrayList or what ever logic you are using. Then just update RecyclerView like this:
blogRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems) && nextPage != null) {
isScrolling = false;
progressBar.setVisibility(View.VISIBLE);
getUsers(mlastNodeId);//here your last id will be
}
}
});
}

RecyclerView blinking on notifyDataSetChanged();

before the moderator take down this question as duplicate please read bellow
Ok I have tried different answers but nothing is working for me for eg I have disabled the animation which doesn't work and I'm trying to use this but I'm not using getItemID so I don't know what to do with it
Here is my Code
Home_Fragment.java // ok I have given only some part of the code that I think is required but if you want to see the entire code please tell me I will update it
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
postRecyclerView.setItemAnimator(null);
getData();
return view;
}
private void getData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
postRecyclerView.setVisibility(View.VISIBLE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
assert upload != null;
upload.setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
postsAdapter.setUploads(mUploads);
//notify the adapter
postsAdapter.notifyDataSetChanged();
loading = true;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
loading = true;
}
});
}
PostAdapter_Home.java
public class PostAdapter_Home extends RecyclerView.Adapter<PostAdapter_Home.PostViewHolder> {
public static List<Upload> mUploads;
public Context mcontext;
public PostAdapter_Home(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(mcontext).inflate(R.layout.ex_home, parent, false);
return new PostViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setBaseColor(Color.parseColor("#F3F3F3"))
.setBaseAlpha(1)
.setHighlightColor(Color.parseColor("#E7E7E7"))
.setHighlightAlpha(1)
.setDropoff(50)
.build();
ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
shimmerDrawable.setShimmer(shimmer);
Upload uploadCurrent = mUploads.get(position);
Glide.with(mcontext)
.load(uploadCurrent.getmImageUrl())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(shimmerDrawable)
.centerCrop()
.fitCenter()
.into(holder.imageView);
// holder.imageView.setOnClickListener(view -> changeScaleType(holder, position));
}
#Override
public int getItemCount() {
return mUploads.size();
}
public void setUploads(List<Upload> uploads){
mUploads=uploads;
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
private final ShapeableImageView imageView;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagePostHome);
}
}
}
Upload.java
package com.example.myappnotfinal.AdaptersAndMore;
import com.google.firebase.database.Exclude;
public class Upload {
private String mImageUrl;
private String mKey;
private String mUserName;
private String mComment;
public Upload() {
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmUserName() {
return mUserName;
}
public void setmUserName(String mUserName) {
this.mUserName = mUserName;
}
public String getmComment() {
return mComment;
}
public void setmComment(String mComment) {
this.mComment = mComment;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
#Exclude
public String getmKey() {
return mKey;
}
#Exclude
public void setmKey(String Key) {
this.mKey = Key;
}
}
Try ListAdapter, it manage these all animations for you. To implement this, we need write some boilerplate classes.
First, let's create the adapter.
public class YourAdapter extends ListAdapter<YourModelClass, YourAdapter.YourViewHolder> {
public YourAdapter(#NonNull DiffUtil.ItemCallback<YourModelClass> diffCallback) {
super(diffCallback);
}
public static class YourViewHolder extends RecyclerView.ViewHolder {
private TextView textViewId;
private TextView textViewName;
private YourViewHolder(View view) {
super(view);
textViewId = view.findViewById(R.id.textViewId);
textViewName = view.findViewById(R.id.textViewName);
}
static YourViewHolder create(ViewGroup parent) {
return new YourViewHolder(
LayoutInflater.from(parent.getContext())
.inflate(
R.layout.your_layout,
parent,
false
)
);
}
void bind(YourModelClass model) {
textViewId.setText(String.valueOf(model.getId()));
textViewName.setText(model.getName());
}
}
#NonNull
#Override
public YourViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return YourViewHolder.create(parent);
}
#Override
public void onBindViewHolder(#NonNull YourViewHolder holder, int position) {
holder.bind(getItem(position));
}
}
now, let's create your class to compare list items with DiffUtill algorithm. In areItemsTheSame you need to use a unique key to compare items. In areContentsTheSame we just compare the both instances.
public class YourItemCallback extends DiffUtil.ItemCallback<YourModelClass> {
#Override
public boolean areItemsTheSame(#NonNull YourModelClass oldItem, #NonNull YourModelClass newItem) {
return oldItem.getId() == newItem.getId();
}
#Override
public boolean areContentsTheSame(#NonNull YourModelClass oldItem, #NonNull YourModelClass newItem) {
return Objects.equals(oldItem, newItem);
}
}
Finally, let's to send data to the adapter. Note that submitList method receive a list of type you specify in adapter
ListAdapter<YourModelClass, YourAdapter.YourViewHolder>
List<YourModelClass> yourList = Arrays.asList(
new YourModelClass(1, "John"),
new YourModelClass(1, "Mac"),
new YourModelClass(1, "Gu"),
new YourModelClass(1, "Gabriel")
);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
YourAdapter yourAdapter = new YourAdapter(new YourItemCallback());
recyclerView.setAdapter(yourAdapter);
yourAdapter.submitList(yourList);

How to implement endless scroll (pagination) in recyclerview with StaggeredGridLayoutManager

Hello there I have a recyclerview with images loaded from firebase I want to implement endless scroll but the issue I'm getting is with StaggeredGridLayoutManager and I have to use it I cant replace it with grid-layout
Note:- I have seen other answers on this topic but the majority of
answers are for LinearLayoutManager and some for GridLayout but there
is only one answer I found for StaggeredGridLayoutManager which I don't
know why it's not working for me
If you want more references of the code please tell me I will update
the question
Profile_Fragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ImageView accountSettings = view.findViewById(R.id.account_Settings);
RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
profilePhoto = relativeLayout.findViewById(R.id.circleImageView);
editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
uploadImageButton = view.findViewById(R.id.upload_image_profile);
progressBar = view.findViewById(R.id.progressBar_Profile);
editProfileButton.setOnClickListener(v -> {
Fragment edit_profile = new Edit_Profile();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, edit_profile);
transaction.addToBackStack(String.valueOf(edit_profile));
transaction.commit();
});
uploadImageButton.setOnClickListener(v -> {
BottomSheet_Upload bottomSheetSettings = new BottomSheet_Upload();
bottomSheetSettings.show(requireActivity().getSupportFragmentManager(), bottomSheetSettings.getTag());
});
accountSettings.setOnClickListener(
v -> {
BottomSheet_Settings bottomSheetSettings = new BottomSheet_Settings();
bottomSheetSettings.show(requireActivity().getSupportFragmentManager(), bottomSheetSettings.getTag());
}
);
postRecyclerView = view.findViewById(R.id.postRecyclerViewProfile);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
postRecyclerView.setLayoutManager(
staggeredGridLayoutManager // I have 3 rows
);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = staggeredGridLayoutManager.getChildCount();
totalItemCount = staggeredGridLayoutManager.getItemCount();
int[] firstVisibleItems = null;
firstVisibleItems = staggeredGridLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);
if (firstVisibleItems != null && firstVisibleItems.length > 0) {
pastVisibleItems = firstVisibleItems[0];
}
if (loading) {
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
loading = false;
getData();
Log.d("tag", "LOAD NEXT ITEM");
}
}
}
});
postRecyclerView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
initImageLoader();
setProfileImage();
mUploads = new ArrayList<>();
postsAdapter = new PostAdapter(getContext(), mUploads);
postRecyclerView.setAdapter(postsAdapter);
postsAdapter.setOnItemClickListener(Profile_Fragment.this);
return view;
}
private void initImageLoader() {
UniversalImageLoader universalImageLoader = new UniversalImageLoader(getContext());
ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
private void setProfileImage() {
String imgUrl = "www.64.media.tumblr.com/1276b4edef49034af70bda14325385e3/d8872c747cafa206-96/s500x750/aa915fc49a84b5295f0cd44145d655b66eb906a6.jpg";
UniversalImageLoader.setImage(imgUrl, profilePhoto, null, "https://");
}
private void getData() {
mStorage = FirebaseStorage.getInstance();
databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
progressBar.setVisibility(View.GONE);
postRecyclerView.setVisibility(View.VISIBLE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
//notify the adapter
postsAdapter.notifyDataSetChanged();
loading = true;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
loading = true;
}
});
}
Update 1
The main question code is changed with the current answer and Added the adapter class as requested
Problem
After implementing the answer there are no errors but the images are not loading in so I have updated the main code with the added answer
PostAdapter.java
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
public static List<Upload> mUploads;
public Context mcontext;
private OnItemClickListener mListener;
/* ShimmerFrameLayout shimmerFrameLayout; */
public PostAdapter(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater.from(mcontext).inflate(R.layout.post_item_container_profile, parent, false);
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item_container_profile, parent, false);
return new PostViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setBaseColor(Color.parseColor("#F3F3F3"))
.setBaseAlpha(1)
.setHighlightColor(Color.parseColor("#E7E7E7"))
.setHighlightAlpha(1)
.setDropoff(50)
.build();
ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
shimmerDrawable.setShimmer(shimmer);
Glide.with(mcontext)
.load(uploadCurrent.getmImageUrl())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(shimmerDrawable)
.centerCrop()
.fitCenter()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public interface OnItemClickListener {
void onClick(View view);
void onItemClick(int position);
void onDeleteClick(int position);
}
public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
ShapeableImageView imageView;
PostViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagePost);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
if (item.getItemId() == 2) {
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
}
For your first problem you already have a solution.
StaggeredGridLayoutManager staggeredGridLayoutManager = new
StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
postRecyclerView.setLayoutManager(
staggeredGridLayoutManager // I have 3 rows
);
For second problem:
postRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener({
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = staggeredGridLayoutManager .getChildCount();
totalItemCount = staggeredGridLayoutManager .getItemCount();
int[] firstVisibleItems = null;
firstVisibleItems = mLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);
if(firstVisibleItems != null && firstVisibleItems.length > 0) {
pastVisibleItems = firstVisibleItems[0];
}
if (loading) {
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
loading = false;
getData()
}
}
}
});
..........
..........
private void getData() {
mStorage = FirebaseStorage.getInstance();
databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
progressBar.setVisibility(View.GONE);
postRecyclerView.setVisibility(View.VISIBLE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
//notify the adapter
postsAdapter.notifyDataSetChanged();
loading = true;
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
loading = true;
}
});
}
You might have to call the getData() initially in your onCreate() so that some data loads up on the screen and you have a scroll behavior.
Update:
The second parameter in a StaggeredGridLayoutManager is orientation so instead of context you have to pass orientation StaggeredGridLayoutManager.VERTICAL.

Pagination not working with staggered grid layout android

Hello im trying to include pagination in my recylerview but dont know why it is not working with
staggeredgrid layout this the question im searching for and becuase the answer are for linearlayoutmanager i got an answer for how to implement pagination in staggerdgrid layoutmanager here is the answer i tried in my code after implementing it the images are not loading
ScreenShot // ss of what im getting right now
short code
int pastVisiblesItems, visibleItemCount, totalItemCount;
int visibleThreshold = 1;
ContentLoadingProgressBar contentLoadingProgressBar;
private boolean isLoading = false;
contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] lastVisibleItemPositions = Objects.requireNonNull(linearLayoutManager).findLastVisibleItemPositions(null);
int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
int totalItemCount = linearLayoutManager.getItemCount();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
getData();
shimmerFrameLayout.startShimmer();
isLoading = true;
}
}
});
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
full code
public class Profile_Fragment extends Fragment implements PostAdapter.OnItemClickListener {
public static List<Upload> mUploads;
private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
PostAdapter postsAdapter;
ShimmerFrameLayout shimmerFrameLayout;
RecyclerView postRecyclerView;
Button editProfileButton;
CircleImageView profilePhoto;
ContentLoadingProgressBar contentLoadingProgressBar;
int visibleThreshold = 1;
private FirebaseStorage mStorage;
private ValueEventListener databaseEventListener;
private boolean isLoading = false;
#SuppressLint("SourceLockedOrientationActivity")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ImageView accountSettings = view.findViewById(R.id.account_Settings);
RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
profilePhoto = relativeLayout.findViewById(R.id.circleImageView);
editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
editProfileButton.setOnClickListener(v -> {
Fragment edit_profile = new Edit_Profile();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, edit_profile);
transaction.addToBackStack(null);
transaction.commit();
});
accountSettings.setOnClickListener(
v -> {
BottomSheet bottomSheet = new BottomSheet();
bottomSheet.show(requireActivity().getSupportFragmentManager(), bottomSheet.getTag());
}
);
postRecyclerView = view.findViewById(R.id.postRecyclerViewProfile);
shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
postRecyclerView.setLayoutManager(
new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
);
final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
assert linearLayoutManager != null;
int[] lastVisibleItemPositions = linearLayoutManager.findLastVisibleItemPositions(null);
int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
int totalItemCount = linearLayoutManager.getItemCount();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
isLoading = true;
getData();
}
}
});
mUploads = new ArrayList<>();
postsAdapter = new PostAdapter(getContext(), mUploads);
postRecyclerView.setAdapter(postsAdapter);
postsAdapter.setOnItemClickListener(Profile_Fragment.this);
return view;
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
private void getData() {
contentLoadingProgressBar.setVisibility(View.VISIBLE);
mStorage = FirebaseStorage.getInstance();
databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
postRecyclerView.setVisibility(View.VISIBLE);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
contentLoadingProgressBar.setVisibility(View.GONE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
//notify the adapter
postsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onItemClick(int position) {
}
#Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
String selectedKey = selectedItem.getmKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getmImageUrl());
imageRef.delete().addOnSuccessListener(aVoid -> {
databaseReference.child(selectedKey).removeValue();
Toast.makeText(getContext(), "Post Deleted", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(aVoid -> Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show());
}
#Override
public void onDestroyView() {
super.onDestroyView();
databaseReference.removeEventListener(databaseEventListener);
}
}
Update 1
added adapter.class
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
public static List<Upload> mUploads;
public Context mcontext;
private OnItemClickListener mListener;
// ShimmerFrameLayout shimmerFrameLayout;
public PostAdapter(Context context, List<Upload> uploads) {
mUploads = uploads;
mcontext = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater.from(mcontext).inflate(R.layout.post_item_container_profile, parent, false);
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item_container_profile, parent, false);
return new PostViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
.setBaseColor(Color.parseColor("#F3F3F3"))
.setBaseAlpha(1)
.setHighlightColor(Color.parseColor("#E7E7E7"))
.setHighlightAlpha(1)
.setDropoff(50)
.build();
ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
shimmerDrawable.setShimmer(shimmer);
Glide.with(mcontext)
.load(uploadCurrent.getmImageUrl())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(shimmerDrawable)
.centerCrop()
.fitCenter()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public interface OnItemClickListener {
void onClick(View view);
void onItemClick(int position);
void onDeleteClick(int position);
}
public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
ShapeableImageView imageView;
PostViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imagePost);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
if (item.getItemId() == 2) {
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
}
Try this.
public class Profile_Fragment extends Fragment implements PostAdapter.OnItemClickListener {
public static List<Upload> mUploads = new ArrayList<>();
private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
PostAdapter postsAdapter = new PostAdapter(getContext(), mUploads);;
ShimmerFrameLayout shimmerFrameLayout;
RecyclerView postRecyclerView;
Button editProfileButton;
CircleImageView profilePhoto;
ContentLoadingProgressBar contentLoadingProgressBar;
int visibleThreshold = 1;
private FirebaseStorage mStorage;
private ValueEventListener databaseEventListener;
private boolean isLoading = false;
#SuppressLint("SourceLockedOrientationActivity")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ImageView accountSettings = view.findViewById(R.id.account_Settings);
RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
profilePhoto = relativeLayout.findViewById(R.id.circleImageView);
editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
editProfileButton.setOnClickListener(v -> {
Fragment edit_profile = new Edit_Profile();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, edit_profile);
transaction.addToBackStack(null);
transaction.commit();
});
accountSettings.setOnClickListener(
v -> {
BottomSheet bottomSheet = new BottomSheet();
bottomSheet.show(requireActivity().getSupportFragmentManager(), bottomSheet.getTag());
}
);
postRecyclerView = view.findViewById(R.id.postRecyclerViewProfile);
shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
postRecyclerView.setLayoutManager(
new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
);
final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
postRecyclerView.setAdapter(postsAdapter);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
assert linearLayoutManager != null;
int[] lastVisibleItemPositions = linearLayoutManager.findLastVisibleItemPositions(null);
int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
int totalItemCount = linearLayoutManager.getItemCount();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
isLoading = true;
getData();
}
postadapter.mUploads=mUploads
postsAdapter.notifyDataSetChanged();
}
});
postsAdapter.setOnItemClickListener(Profile_Fragment.this);
return view;
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
private void getData() {
contentLoadingProgressBar.setVisibility(View.VISIBLE);
mStorage = FirebaseStorage.getInstance();
databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
postRecyclerView.setVisibility(View.VISIBLE);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
contentLoadingProgressBar.setVisibility(View.GONE);
mUploads.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
mUploads.add(upload);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onItemClick(int position) {
}
#Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
String selectedKey = selectedItem.getmKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getmImageUrl());
imageRef.delete().addOnSuccessListener(aVoid -> {
databaseReference.child(selectedKey).removeValue();
Toast.makeText(getContext(), "Post Deleted", Toast.LENGTH_SHORT).show();
})
.addOnFailureListener(aVoid -> Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show());
}
#Override
public void onDestroyView() {
super.onDestroyView();
databaseReference.removeEventListener(databaseEventListener);
}
}
Let me Know if not working.....

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.

Categories

Resources