Losing data when refresh RecyclerView - java

I have two List<> instances, I clear both lists then my data is lost. I clear it using this code:
private List<ContentProfileDashboard> contentListDashboard;
private AdapterProfileDashboard adapterProfileDashboard;
private ContentProfileDashboard contentProfileDashboard;
....
// button in MainFragment not in Adapter
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this is first list that i clear
contentListDashboard.clear();
// this is second list that i clear from Adapter class List<ContentProfileDashboard> contentList;
adapterProfileDashboard.contentList.clear();
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
This is MainFragment named ProfileFragment.class
public class ProfileFragment extends Fragment {
//private RecyclerView recyclerSeen;
private RecyclerView recyclerProfileDashboard;
//private List<ContentProfile> contentList;
private List<ContentProfileDashboard> contentListDashboard;
//private AdapterSeenProfileDashboard adapterSeen;
private AdapterProfileDashboard adapterProfileDashboard;
private Boolean isFirstPageFirstLoad = true;
//private ContentProfile contentSeen;
private ContentProfileDashboard contentProfileDashboard;
private Boolean allowRefresh = true;
private CircleImageView profileImage;
private CircleImageView profileStatusImage;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private DocumentSnapshot lastVisible;
private View view;
private TextView profileNickName;
private TextView profileLongName;
private TextView profileStatusIsActive;
private Button buttonRefresh;
private int currentItems, totalItems, scrollOutItems;
private LinearLayoutManager manager;
private Boolean isScrolling = false;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
//firebaseAuth = FirebaseAuth.getInstance();
Toolbar toolbar = view.findViewById(R.id.toolbarProfile);
// toolbar.setTitle("Rashid");
profileImage = view.findViewById(R.id.circleImageProfile);
profileNickName = view.findViewById(R.id.nick_name);
profileLongName = view.findViewById(R.id.long_name);
profileStatusIsActive = view.findViewById(R.id.status_active);
profileStatusImage = view.findViewById(R.id.circleImageStatus);
profilePosition = view.findViewById(R.id.position_in_company);
//for crate home button
AppCompatActivity activity = (AppCompatActivity) getActivity();
//MainActivity activity = (MainActivity) getActivity(); // MainActivity cannot be cast to android.support.v7.app.ActionBarActivity
if (activity != null) {
activity.setSupportActionBar(toolbar);
if (activity.getSupportActionBar() != null) {
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(false); // back button
activity.getSupportActionBar().setDisplayShowHomeEnabled(true);
activity.getSupportActionBar().setIcon(R.drawable.googleg_disabled_color_18);
activity.getSupportActionBar().setTitle("");
}
}
setHasOptionsMenu(true);
//contentList = new ArrayList<>();
contentListDashboard = new ArrayList<>();
recyclerProfileDashboard = view.findViewById(R.id.recycler_dashboard_profile);
//horizontal
//recyclerSeen = view.findViewById(R.id.recycler_seenBy);
//adapterSeen = new AdapterSeenProfileDashboard(contentList);
adapterProfileDashboard = new AdapterProfileDashboard(contentListDashboard);
//vertical
// recyclerSeen = view.findViewById(R.id.recycler_dashboard_profile);
// recyclerSeen.setLayoutManager(new LinearLayoutManager(container.getContext()));
manager = new LinearLayoutManager(container.getContext());
recyclerProfileDashboard.setLayoutManager(manager);
//horizontal
//recyclerSeen.setLayoutManager(new LinearLayoutManager(container.getContext(), LinearLayoutManager.HORIZONTAL, false));
// vertical
//recyclerSeen.setAdapter(adapterSeen);
recyclerProfileDashboard.setAdapter(adapterProfileDashboard);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(), Register.class);
// startActivity(intent); // make sr crash from DesignIn not from intent
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.update(contentListDashboard);
}
});
// CHECK 2
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contentListDashboard.clear();
adapterProfileDashboard.contentList.clear();
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
// CHECK 2
profileLongName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapterProfileDashboard.contentList.clear();
adapterProfileDashboard.contentList.addAll(contentListDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
loadFirstQuery();
}
public void loadFirstQuery() {
if (firebaseAuth.getCurrentUser() != null) {
contentListDashboard.clear();
String currentUserId = firebaseAuth.getCurrentUser().getUid();
firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult() != null) {
String image = task.getResult().getString("image");
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_profile_off);
Glide.with(Objects.requireNonNull(getActivity())).applyDefaultRequestOptions(requestOptions).load(image).into(profileImage);
String nickName = task.getResult().getString("nickName");
profileNickName.setText(nickName);
String longName = task.getResult().getString("longName");
profileLongName.setText(longName);
String status = task.getResult().getString("status");
if (status != null) {
if (status.equals("ACTIVE")){
profileStatusIsActive.setText(status);
profileStatusImage.setImageResource(R.color.colorAccent);
} else {
profileStatusIsActive.setText(status);
profileStatusImage.setImageResource(R.color.darkGrey);
}
}
String position = task.getResult().getString("position");
profilePosition.setText(position);
}
}
}
});
// recyclerProfileDashboard.addOnScrollListener(new RecyclerView.OnScrollListener() {
// #Override
// public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
// super.onScrolled(recyclerView, dx, dy);
// // horizontal
// //Boolean reachBottom = !recyclerView.canScrollHorizontally(-1);
// // vertical
// Boolean reachBottom = !recyclerView.canScrollVertically(-1);
// if (reachBottom) {
// loadMorePost();
// }
// }
// });
// TRY NEW SCROLL METHOD
recyclerProfileDashboard.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)) {
isScrolling = false;
// implement progress bar here
loadMorePost();
}
}
});
// RETRIEVING SEEN
Query firstQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(5);
// Activity.this if not fragment /// Objects.requireNonNull(getActivity()),
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
// please add if doc not empty
if (isFirstPageFirstLoad) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1); // array 0, 1, 2
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
if (isFirstPageFirstLoad) {
contentListDashboard.add(contentProfileDashboard);
} else {
contentListDashboard.add(0, contentProfileDashboard);
}
// fire the event
adapterProfileDashboard.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
}
});
}
}
public void loadMorePost() {
if (firebaseAuth.getCurrentUser() != null) {
String currentUserId = firebaseAuth.getCurrentUser().getUid();
Query nextQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.startAfter(lastVisible)
.limit(5);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
// contentSeen = doc.getDocument().toObject(ContentProfile.class);
// contentList.add(contentSeen);
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
contentListDashboard.add(contentProfileDashboard);
//adapterSeen.notifyDataSetChanged();
adapterProfileDashboard.notifyDataSetChanged();
}
}
}
}
});
}
}
This is Adapter
public class AdapterProfileDashboard extends RecyclerView.Adapter<AdapterProfileDashboard.ViewHolder> {
public List<ContentProfileDashboard> contentList;
public Context context;
public AdapterProfileDashboard(List<ContentProfileDashboard> contentList){
this.contentList = contentList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_profile_dashboard, parent, false);
context = parent.getContext(); // or add in parameter constructor this.context = context; and set in HomeFragment AdapterFragmentHome(container.getContext(), contentList);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setIsRecyclable(false);
String text = contentList.get(position).getProfileText();
holder.setUserText(text);
}
#Override
public int getItemCount() {
return contentList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView userProfile;
//private TextView textDashboard;
public ViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setUserText(String text) {
userProfile = mView.findViewById(R.id.profile_text_dashboard);
userProfile.setText(text);
}
}
}
my question is how to refresh recycle view correctly?.. so my data not lost?

Related

Firebase Messages get count badge The Unread new Messages Recived

I use Firebase to send messages between users, and I'd like to use a new unread message badge and the number of unread messages.
I want to help solve this problem so I can get the number of unread messages when they are received from the other user and displayed in the user's list
like this
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
Typeface MR,MRR;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
public View view_click;
FirebaseUser fuser;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl){
this.mChat = mChat;
this.mContext = mContext;
this.imageurl = imageurl;
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setTypeface(MRR);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
chat.setSelected(!chat.isSelected());
holder.view.setBackgroundColor(chat.isSelected() ? Color.TRANSPARENT : Color.WHITE);
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
// holder.delete.setVisibility(View.VISIBLE);
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.po);
LinearLayout copy = dialog.findViewById(R.id.copy);
LinearLayout share = dialog.findViewById(R.id.share);
LinearLayout reply = dialog.findViewById(R.id.reply);
LinearLayout delete = dialog.findViewById(R.id.remove_item);
copy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", chat.getMessage());
clipboard.setPrimaryClip(clip);
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
snackbar.show();
dialog.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, chat.getMessage() );
mContext. startActivity(Intent.createChooser(intent2, "Share via"));
dialog.dismiss();
}
});
reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view_click) {
FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Chats")
.child(chat.getChatid())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
View view;
final Snackbar snackbar = Snackbar.make(holder.lyt_parent, "", Snackbar.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.snack_delete, null);
snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
snackBarView.setPadding(0, 0, 0, 0);
snackBarView.addView(view, 0);
dialog.dismiss();
snackbar.show();
// Toast.makeText(mContext, "Deleted! ="+chat.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.setCancelable(true);
dialog.show();
/*
*/
}
}
);
holder.show_message.setText(chat.getMessage());
if(chat.getTime()!=null && !chat.getTime().trim().equals("")) {
holder.time_tv.setText(holder.convertTime(chat.getTime()));
}
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
if (position == mChat.size()-1){
if (chat.isIsseen()){
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24);
} else {
// holder.seen.setImageResource(R.drawable.ic_baseline_check_24_read);
}
} else {
// holder.seen.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView show_message;
public ImageView profile_image,seen,delete;
public TextView time_tv;
public Dialog myDialog;
public View view_click;
public LinearLayout lyt_parent;
private View view;
public ViewHolder(View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
time_tv = itemView.findViewById(R.id.time_tv);
seen = itemView.findViewById(R.id.seen);
view = itemView;
lyt_parent= itemView.findViewById(R.id.lyt_parent);
}
public String convertTime(String time){
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
String dateString = formatter.format(new Date(Long.parseLong(time)));
return dateString;
}
}
#Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
item Uaer Massage
public class UserAdaptermsg extends RecyclerView.Adapter<UserAdaptermsg.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
private OnItemClick onItemClick;
Typeface MR,MRR;
String theLastMessage;
boolean isopend ;
public UserAdaptermsg(Context mContext, OnItemClick onItemClick, List<User> mUsers, boolean ischat){
this.onItemClick = onItemClick;
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
if(mContext!=null) {
MRR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriadregular.ttf");
MR = Typeface.createFromAsset(mContext.getAssets(), "fonts/myriad.ttf");
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_msg, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final User user = mUsers.get(position);
// holder.username.setTypeface(MR);
holder.last_msg.setTypeface(MRR);
holder.badg_massage.setVisibility(View.GONE);
holder.username.setText(user.getFullname());
if (user.getImageurl().equals("default")){
holder.profile_image.setImageResource(R.drawable.ic_profile_outline_40);
} else {
Glide.with(mContext).load(user.getImageurl()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
count(user.getId(),true);
// holder.badg_massage.setVisibility(View.VISIBLE);
// holder.badg_massage.setText(mUsers.size()+"");
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat){
if (user.getStatus().equals("online")){
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.onItemCLick(user.getId(),view);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
private TextView badg_massage;
public ViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
badg_massage = itemView.findViewById(R.id.badg_massage);
}
}
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void count(final String userid, final Boolean count){
isopend = false;
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
isopend = chat.isIsopened();
}
}
}
if (isopend == false) {
Toast.makeText(mContext, "notopent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "isopend", Toast.LENGTH_SHORT).show();
}
isopend = true;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
model Chat
package com.Model;
public class Chat {
private String sender;
private String receiver;
private String message;
private boolean isseen;
private String chatid;
private boolean isSelected = false;
private boolean isopened;
private String time;
public Chat(String sender, String receiver, String message, boolean isseen, String chatid, boolean isopened, String time) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.isseen = isseen;
this.chatid = chatid;
this.isopened = isopened;
this.time = time;
}
public Chat() {
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getChatid() {
return chatid;
}
public void setChatid(String chatid) {
this.chatid = chatid;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isIsopened() {
return isopened;
}
public void setIsopened(boolean isopened) {
this.isopened = isopened;
}
}

Transition between 2 recycler views having cards

I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.

RecyclerView: different ViewType by different button

I have a recycler view to show an activity timeline and three floating buttons that click to add activity. How can I code three buttons to a different view? How can I pass the condition to the Adapter?
Now I can show only one viewType.
thx a lot.
Adapter.java
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolder> {
private List<Trip> trips = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public TripHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TripHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewLodgingTitle.setText(currentTrip.getLodgingTitle());
holder.textTextViewLodgingCheckInDateTime.setText(currentTrip.getLodgingCheckInDateTime());
holder.textTextViewLodgingCheckOutDateTime.setText(currentTrip.getLodgingCheckOutDateTime());
holder.textViewLodgingAddress.setText(currentTrip.getLodgingAddress());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolder extends RecyclerView.ViewHolder {
//lodging
private TextView textViewLodgingTitle;
private TextView textTextViewLodgingCheckInDateTime;
private TextView textTextViewLodgingCheckOutDateTime;
private TextView textViewLodgingAddress;
private TextView textViewLodgingPhone;
private TextView textViewLodgingWebsite;
private TextView textViewLodgingEmail;
public TripHolder(#NonNull View itemView) {
super(itemView);
context = itemView.getContext();
textViewLodgingTitle = itemView.findViewById(R.id.text_view_title);
textTextViewLodgingCheckInDateTime = itemView.findViewById(R.id.text_view_start_date_time);
textTextViewLodgingCheckOutDateTime = itemView.findViewById(R.id.text_view_end_date_time);
textViewLodgingAddress = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(trips.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Trip trip);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
MainActivity.java
//adapter
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter );
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
//this on onActivityResult()
else if (requestCode == ADD_LODGING && resultCode == Activity.RESULT_OK) {
//get data from lodging activity
String lodgingTitle = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_TITLE);
String lodgingCheckInDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_IN_DATE_TIME);
String lodgingCheckOutDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_OUT_DATE_TIME);
String lodgingDescription = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_DESCRIPTION);
String lodgingAddress = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_ADDRESS);
String lodgingPhone = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_PHONE);
String lodgingWebsite = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_WEBSITE);
String lodgingEmail = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_EMAIL);
String lodgingImagePath = "test";
Trip lodging = new Trip(lodgingTitle, lodgingCheckInDateTime, lodgingCheckOutDateTime,lodgingDescription, lodgingAddress, lodgingPhone, lodgingWebsite, lodgingEmail,lodgingImagePath);
tripViewModel.insert(lodging);
Toast.makeText(this, "lodging save", Toast.LENGTH_SHORT).show();
}
My application I adapt from codinginflow channel.
https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction

Why I cannot pass data from RecyclerView to another RecyclerView - AndroidX

I want to make data from RecyclerView1 Activity1 can be passed to RecyclerView2 Activity2
//SectionAdapter.java
public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
intent.putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
} });
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//SingleAdapter.java
public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
return new SingleHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//ModelSection.java
public class ModelSectionHotTrendingNews implements Serializable {
private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;
public ModelSectionHotTrendingNews() {
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
//ModelSingle.java
public class ModelSingleHotTrendingNews implements Serializable {
private int id;
private String gamedate;
private String gamedescription;
private int gameimage;
private Boolean trendingnewssaving;
private String value;
private String message;
public ModelSingleHotTrendingNews(int id, String gamedate, String gamedescription, int gameimage, Boolean trendingnewssaving, String value, String message) {
this.id = id;
this.gamedate = gamedate;
this.gamedescription = gamedescription;
this.gameimage = gameimage;
this.trendingnewssaving = trendingnewssaving;
this.value = value;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getGameimage() {
return gameimage;
}
public void setGameimage(int gameimage) {
this.gameimage = gameimage;
}
public Boolean getTrendingnewssaving() {
return trendingnewssaving;
}
public void setTrendingnewssaving(Boolean trendingnewssaving) {
this.trendingnewssaving = trendingnewssaving;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//AdapterMoreSection.java
public class AdapterMoreSectionHotTrendingNews extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterMoreSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemmore_section_hottrendingnews, null);
return new SectionMoreHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleMoreSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterMoreSingleHotTrendingNews itemListDataAdapter = new AdapterMoreSingleHotTrendingNews(mContext, singleMoreSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionMoreHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() {
#Override public void onClick(View v) {
//More IN RecyclerViewMore
}
});
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setHasFixedSize(true);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//AdapterMoreSingle.java
public class AdapterMoreSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterMoreSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemmore_single_hottrendingnews, null);
return new SingleMoreHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleMoreHotTrendingNewsViewHolder singleMoreHotTrendingNewsViewHolder = (SingleMoreHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleMoreHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleMoreHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleMoreHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleMoreHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//Activity2More.java
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
//Error
Process: com.indofun.android.indojoy, PID: 18827
java.lang.ClassCastException: com.indofun.android.indojoy.Models.Model_HotTrendingNews.ModelSingleHotTrendingNews cannot be cast to com.indofun.android.indojoy.Models.Model_HotTrendingNews.ModelSectionHotTrendingNews
at com.indofun.android.indojoy.Adapters.AdapterMore_HotTrendingNews.AdapterMoreSectionHotTrendingNews.onBindViewHolder(AdapterMoreSectionHotTrendingNews.java:39)
//NOTE
//RecyclerView1 using AdapterSection.java,AdapterSingle.java,ModelSection.java,ModelSingle.java
//RecyclerView2 using AdapterMoreSection.java,AdapterMoreSingle.java,ModelSection.java,ModelSingle.java
Inside TabMoreHotActivity use like this:
ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null {
modelSingleHotTrendingNews = ArrayList<ModelSingleHotTrendingNews>) bundle.getSerializable("MoreNews");
}

RecyclerView doesn't display all items from Firestore Query

I made an Activity that displays the list of Users (order by name) in a RecyclerView. And the RecyclerView works well for the first Users but never displays the last User of the list and it's very strange because It should load all the data.
public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.ViewHolder> {
public List<Users> usersList;
public Context context;
public UsersRecyclerAdapter(Context context, List<Users> usersList){
this.usersList = usersList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.nameText.setText(usersList.get(position).getName());
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.baseline_account_circle_black_24);
Glide.with(holder.nameText.getContext().getApplicationContext()).applyDefaultRequestOptions(requestOptions).load(usersList.get(position).getImage()).into(holder.profileImage);
final String user_id = usersList.get(position).userId;
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(v.getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
profileIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(profileIntent);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
View mView;
public TextView nameText;
public CircleImageView profileImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
nameText = mView.findViewById(R.id.search_user_name);
profileImage = mView.findViewById(R.id.search_user_image);
}
}
}
public class UsersActivity extends AppCompatActivity {
private RecyclerView users_list_view;
private List<Users> users_list;
private Toolbar mToolbar;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private UsersRecyclerAdapter usersRecyclerAdapter;
private DocumentSnapshot lastVisible;
private Boolean isFirstPageFirstLoad = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar = findViewById(R.id.new_post_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(R.string.all_users);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
users_list = new ArrayList<>();
users_list_view = findViewById(R.id.users_list_view);
firebaseAuth = FirebaseAuth.getInstance();
usersRecyclerAdapter = new UsersRecyclerAdapter(getApplicationContext(), users_list);
users_list_view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
users_list_view.setAdapter(usersRecyclerAdapter);
users_list_view.setHasFixedSize(true);
if (firebaseAuth.getCurrentUser() != null) {
firebaseFirestore = FirebaseFirestore.getInstance();
users_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Boolean reachedBottom = !recyclerView.canScrollVertically(1);
if (reachedBottom) {
loadMorePost();
}
}
});
Query firstQuery = firebaseFirestore.collection("Users").orderBy("name", Query.Direction.ASCENDING).limit(3);
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
if (isFirstPageFirstLoad) {
lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
users_list.clear();
}
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String userId = doc.getDocument().getId();
Users user = doc.getDocument().toObject(Users.class).withId(userId);
if (isFirstPageFirstLoad) {
users_list.add(user);
} else {
users_list.add(0, user);
}
usersRecyclerAdapter.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
private void loadMorePost() {
if(firebaseAuth.getCurrentUser() != null) {
Query nextQuery = firebaseFirestore.collection("Users")
.orderBy("name", Query.Direction.ASCENDING)
.startAfter(lastVisible)
.limit(3);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String userId = doc.getDocument().getId();
Users user = doc.getDocument().toObject(Users.class).withId(userId);
users_list.add(user);
usersRecyclerAdapter.notifyDataSetChanged();
}
}
}
}
});
}
}
}
I think that It's a problem with the Firestore Query but I've never seen this before
I would be very grateful for your help :)

Categories