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 :)
Related
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;
}
}
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");
}
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?
I mean how to make the adapter work not with the model class, but with the already created ArrayList (randomPlaceList)? I take 20 records from my Firestore and put 3 random of them to the ArrayList(randomPlaceList). And now, I want that my adapter connect ViewHolder object not with the model class(Places.class), but with this early created ArrayList(randomPlaceList), where I have already 3 random records..
RecycleView class:
public class Myactivity extends AppCompatActivity {
public RecyclerView mResultList;
public FirebaseFirestore mFirestore;
public com.google.firebase.firestore.Query query;
public FirestoreRecyclerAdapter<Places, PlaceViewHolder> firestoreRecyclerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycle_activity);
mResultList = findViewById(R.id.list_result);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
Boolean l_check2 = getIntent().getExtras().getBoolean("2");
Boolean l_check3 = getIntent().getExtras().getBoolean("3");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("colour", "1").limit(20);
//QUESTION START HERE
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
int randomNumber = new Random().nextInt(placeCount);
//THIS ARRAYLIST I WANT TO USE INSTEAD THE PLACES.CLASS
List<Places> randomPlaceList = new ArrayList<>();
for (int i=1; i<=3; i++) {
randomPlaceList.add(placesList.get(randomNumber));
}
}
}
});
} else if (l_check2) {
query = mFirestore.collection("Places").whereEqualTo("colour", "2").limit(3);
} else if (l_check3) {
query = mFirestore.collection("Places").whereEqualTo("colour", "3").limit(3);
}
mResultList.setLayoutManager(new LinearLayoutManager(this));
FirestoreRecyclerOptions<Places> options = new FirestoreRecyclerOptions.Builder<Places>()
.setQuery(query, Places.class)
.build();
firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<Places, PlaceViewHolder>(options) {
#Override
protected void onBindViewHolder(PlaceViewHolder holder, int position, Places model) {
holder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
return new PlaceViewHolder(view);
}
};
mResultList.setAdapter(firestoreRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firestoreRecyclerAdapter.startListening();
}
class PlaceViewHolder extends RecyclerView.ViewHolder {
View mView;
public PlaceViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context context, String placeName, String placeImage) {
final TextView place_Name = mView.findViewById(R.id.text_image_id);
ImageView place_Image = mView.findViewById(R.id.image_id);
place_Name.setText(placeName);
Glide.with(context).load(placeImage).into(place_Image);
place_Name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Card_activity.class);
intent.putExtra("qwerty", place_Name.getText());
startActivity(intent);
}
});
}
}
#Override
protected void onStop() {
super.onStop();
if (firestoreRecyclerAdapter != null) {
firestoreRecyclerAdapter.stopListening();
}
}
}
And that model class, that used in OnCreate method, for query, but I need to use in Adapter, randomPlaceList to take 3 records, that already put earlier in it. In other words, use 2 model class, if I can say so..:
My Model class:
public class Places {
private String image, name;
public Places() { }
public Places(String image, String name) {
this.image = image;
this.name = name;
}
public String getImage() { return image; }
public String getName() { return name; }
}
EDITED WITH LISTVIEW:
MyListAdaper:
class MyListAdapter extends ArrayAdapter {
public MyListAdapter(Context context, int resource,List<Places> randomPLaceList) {
super(context, 0, randomPLaceList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_list, parent, false);
}
TextView place_Name = convertView.findViewById(R.id.text_image_id);
ImageView place_Image = convertView.findViewById(R.id.image_id);
Places places = (Places) getItem(position);
place_Name.setText(places.getName());
Glide.with(getContext()).load(places.getImage()).into(place_Image);
return convertView;
}
}
ListViewPlaces.class:
public class ListViewPlaces extends AppCompatActivity {
public ListView mListView;
public MyListAdapter myListAdapter;
public FirebaseFirestore mFirestore;
public Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_places);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("meet", "1").whereEqualTo("cash", "1").limit(7);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
//mListView = findViewById(R.id.place_list);
//mListView.setAdapter(myListAdapter);
final int placeCount = placesList.size();
final Random randomGenerator = new Random();
List<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
MyListAdapter mListAdapter = new MyListAdapter(this, randomPlaceList);
mListView.setAdapter(mListAdapter);
}
}
});
}
}
}
Error:
error: constructor MyListAdapter in class MyListAdapter cannot be
applied to given types; required: Context,int,List found:
>,List reason:
actual and formal argument lists differ in length
I need to chceck if all items on adapter have a boolean value = true
Then based on result i have to change floatingActionButton color.
I have no idea how to do it.
Here is my Adapter:
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference basementReference = db.collection("basement");
private TableAdapter tableAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton basement = findViewById(R.id.button_basement);
basement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
setUpRecyclerView();
}
private void setUpRecyclerView(){
final Query query = basementReference.orderBy("tableNumber",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Table> options = new FirestoreRecyclerOptions.Builder<Table>()
.setQuery(query, Table.class)
.build();
tableAdapter = new TableAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(tableAdapter); tableAdapter.setOnItemClickListener(new TableAdapter.OnItemCLickListener() {
#Override
public void onItemClick(final DocumentSnapshot documentSnapshot, int position) {
Table table = documentSnapshot.toObject(Table.class);
if(table.isTableOccupied()){
basementReference.document(documentSnapshot.getId()).update("tableOccupied",false).addOnCompleteListener(new OnCompleteListener<Void>() {
}else {
basementReference.document(documentSnapshot.getId()).update("tableOccupied",true).addOnCompleteListener(new OnCompleteListener<Void>() {
}
#Override
protected void onStart() {
super.onStart();
tableAdapter.startListening();
}
please help. i tthink i need to do it in my adapter class, but if there is other solution i'll be glad to follow :)
tableAdapter class:
class TableAdapter extends FirestoreRecyclerAdapter {
public TableAdapter(#NonNull FirestoreRecyclerOptions<Table> options) {
super(options);
}
private OnItemCLickListener onItemCLickListener;
private int occupiedMarker = 0;
#Override
protected void onBindViewHolder(#NonNull TableHolder holder, int position, #NonNull Table model) {
holder.textViewTableNumber.setText(model.getTableNumber());
holder.textViewTableSeats.setText(model.getTableSeats());
holder.textViewTableOccupied.setText(String.valueOf(model.isTableOccupied()));
}
#NonNull
#Override
public TableHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_table,parent,false);
return new TableHolder(v);
}
class TableHolder extends RecyclerView.ViewHolder{
TextView textViewTableNumber;
TextView textViewTableSeats;
TextView textViewTableOccupied;
public TableHolder(#NonNull View itemView) {
super(itemView);
textViewTableNumber = itemView.findViewById(R.id.text_view_table_number);
textViewTableSeats = itemView.findViewById(R.id.text_view_table_seats);
textViewTableOccupied = itemView.findViewById(R.id.text_view_table_occupied);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && onItemCLickListener!=null){
onItemCLickListener.onItemClick( getSnapshots().getSnapshot(position), position );
}
}
});
}
}
public interface OnItemCLickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemCLickListener onItemClickListener){
this.onItemCLickListener = onItemClickListener;
}
}