Firebase Messages get count badge The Unread new Messages Recived - java

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

Related

How can we save all images and videos on button click in recyclerview?

I am creating activity like WhatsApp to edit photos.Add text, sticker and paint on image.
when click on sendbtn only current image save not all the images.
My question is how to save all images on sendBtn click.Please help me.
Screenshot link
https://i.stack.imgur.com/Jr3ZY.jpg
Thanks in advance.
Here is my adapter.
private final List<FilePickerModel> list;
Context context;
private final String from;
private final String name;
private int pos;
private RecyclerView mediaRv;
int IMAGE_ITEM = 1;
int VIDEO_ITEM = 2;
private VideoView videoView;
private videoHolder holder;
private FilePickerActivity activity;
public MediaAdapter(List<FilePickerModel> list, Context context,RecyclerView mediaRv,String from,String name) {
this.list = list;
this.context = context;
this.mediaRv = mediaRv;
this.from = from;
this.name = name;
}
public void stopPlayer(){
if (holder.mVideoView != null){
holder.mVideoView.stopPlayback();
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == IMAGE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.media_item, parent, false);
return new imageHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_media_item, parent, false);
return new videoHolder(view);
}
}
#Override
public int getItemViewType(int position) {
if (list.get(position).getName().contains(".mp4")) {
return VIDEO_ITEM;
} else {
return IMAGE_ITEM;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
FilePickerModel model = list.get(position);
activity = new FilePickerActivity();
if (holder.getClass() == imageHolder.class) {
//IMAGE_ITEM
EmojiPopup popup = EmojiPopup.Builder.fromRootView(((imageHolder)holder).rootView).build(((imageHolder)holder).captionEDt);
((imageHolder)holder).emojiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.toggle();
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}
});
if (popup.isShowing()){
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}else {
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_keyboard_24);
}
((imageHolder)holder).receiverName.setText(name);
SelectedAdapter adapter = new SelectedAdapter(list,mediaRv);
((imageHolder)holder).recyclerView.setAdapter(adapter);
((imageHolder)holder).deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int newPosition = holder.getAdapterPosition();
list.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, list.size());
adapter.notifyDataSetChanged();
}
});
try {
Uri imageUri = Uri.fromFile(model.getFile());
Bitmap bitmap = MediaStore.Images.Media.getBitmap(holder.itemView.getContext().getContentResolver(), imageUri);
((imageHolder) holder).photoEditorView.getSource().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
((imageHolder) holder).captionEDt.setText(model.getCaption());
((imageHolder) holder).captionEDt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
model.setCaption(editable.toString());
}
});
((imageHolder) holder).mPhotoEditor = new PhotoEditor.Builder(context, ((imageHolder) holder).photoEditorView)
.setPinchTextScalable(true)
.build();
((imageHolder) holder).colorPickerView.setOnColorChangeListener(
new VerticalSlideColorPicker.OnColorChangeListener() {
#Override
public void onColorChange(int selectedColor) {
((imageHolder) holder).mSelectedColor = selectedColor;
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).imagePhotoEditPaint.setBackgroundColor(selectedColor);
((imageHolder) holder).mPhotoEditor.setBrushColor(selectedColor);
}
}
});
((imageHolder) holder).imagePhotoEditBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((AppCompatActivity) context).finish();
}
});
((imageHolder) holder).imagePhotoEditUndo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).mPhotoEditor.undo();
}
});
((imageHolder) holder).imagePhotoEditSticker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).ShowBrush(false);
((imageHolder) holder).mStickerBSFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), ((imageHolder) holder).mStickerBSFragment.getTag());
}
});
((imageHolder) holder).imagePhotoEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextEditorDialogFragment textEditorDialogFragment = TextEditorDialogFragment.show((AppCompatActivity) context);
textEditorDialogFragment.setOnTextEditorListener(new TextEditorDialogFragment.TextEditor() {
#Override
public void onDone(String inputText, int colorCode) {
((imageHolder) holder).mPhotoEditor.addText(inputText, colorCode);
}
});
}
});
((imageHolder) holder).imagePhotoEditPaint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).ShowBrush(false);
} else {
((imageHolder) holder).ShowBrush(true);
}
}
});
((imageHolder) holder).sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
if (from.equals("community")) {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Public/Edonomy Images"));
} else {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Chat/Edonomy Images"));
}
intent.putExtra("media", (Serializable) list);
((MediaEditActivity) context).setResult(RESULT_OK, intent);
((MediaEditActivity) context).finish();
((MediaEditActivity)context).overridePendingTransition(android.R.anim.fade_in,
android.R.anim.fade_out);
}
});
} else {
//VIDEO_ITEM
}
}
#Override
public int getItemCount() {
return list.size();
}
static class imageHolder extends RecyclerView.ViewHolder implements StickerBSFragment.StickerListener {
private final ImageView imagePhotoEditBack;
private final ImageView imagePhotoEditUndo;
private final ImageView imagePhotoEditSticker;
private final ImageView imagePhotoEditText;
private final ImageView imagePhotoEditPaint;
private final StickerBSFragment mStickerBSFragment;
private final VerticalSlideColorPicker colorPickerView;
private final PhotoEditorView photoEditorView;
private PhotoEditor mPhotoEditor;
private int mSelectedColor;
private final EmojiEditText captionEDt;
private final ImageView sendBtn;
private final ImageView deleteBtn;
private final RecyclerView recyclerView;
private final EmojiTextView receiverName;
private final ImageView emojiBtn;
private final LinearLayout rootView;
private boolean isShown = true;
public imageHolder(#NonNull View itemView) {
super(itemView);
imagePhotoEditBack = itemView.findViewById(R.id.img_photo_edit_back);
imagePhotoEditUndo = itemView.findViewById(R.id.img_photo_edit_undo);
ImageView imagePhotoEditRedo = itemView.findViewById(R.id.img_photo_edit_redo);
ImageView imagePhotoEditCrop = itemView.findViewById(R.id.img_photo_edit_crop);
imagePhotoEditSticker = itemView.findViewById(R.id.img_photo_edit_stickers);
imagePhotoEditText = itemView.findViewById(R.id.img_photo_edit_text);
imagePhotoEditPaint = itemView.findViewById(R.id.img_photo_edit_paint);
colorPickerView = itemView.findViewById(R.id.color_picker_view);
sendBtn = itemView.findViewById(R.id.media_send_Btn);
photoEditorView = itemView.findViewById(R.id.media_photo_editor_view);
captionEDt = itemView.findViewById(R.id.media_captionBox);
recyclerView = itemView.findViewById(R.id.select_list_rv);
deleteBtn = itemView.findViewById(R.id.img_photo_delete);
receiverName = itemView.findViewById(R.id.receiver_name_tv);
emojiBtn = itemView.findViewById(R.id.emoji_media_btn);
rootView = itemView.findViewById(R.id.image_emoji_layout);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(itemView.getContext());
layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager1);
mStickerBSFragment = new StickerBSFragment();
mStickerBSFragment.setStickerListener(this);
}
private void ShowBrush(boolean enableBrush) {
if (enableBrush) {
mPhotoEditor.setBrushColor(mSelectedColor);
imagePhotoEditPaint.setBackgroundColor(mSelectedColor);
mPhotoEditor.setBrushDrawingMode(true);
colorPickerView.setVisibility(View.VISIBLE);
} else {
imagePhotoEditPaint.setBackgroundColor(itemView.getContext().getResources().getColor(android.R.color.transparent));
mPhotoEditor.setBrushDrawingMode(false);
colorPickerView.setVisibility(View.INVISIBLE);
}
}
#Override
public void onStickerClick(Bitmap bitmap) {
mPhotoEditor.addImage(bitmap);
}
#SuppressLint("MissingPermission")
public String saveImage(String path) {
File folder = new File(Environment.getExternalStorageDirectory().toString() + path);
if (!folder.isDirectory()) {
folder.mkdirs();
}
File file = new File(folder
+ File.separator + ""
+ System.currentTimeMillis() + ".png");
try {
file.createNewFile();
SaveSettings saveSettings = new SaveSettings.Builder()
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(String.valueOf(file), saveSettings, new PhotoEditor.OnSaveListener() {
#Override
public void onSuccess(#NonNull String imagePath) {
// Toast.makeText(itemView.getContext(), "Image Saved Successfully", Toast.LENGTH_SHORT).show();
/**
* send result back to the ImagePickActivity
*/
}
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(itemView.getContext(), "Failed to save Image", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(itemView.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return String.valueOf(file);
}
}

How I connect recyclerview to firebase database insert,update and delete data

I create an app which contain recyclerview and I add data in recyclerview arrayList from alertDilog and edit,delete data from AlertDilog according to the user click .It works properly but when I connect my app to firebase Database, my app doesn't work properly.
Recyclerview Adapter:
public class recyclerviewadapter extends RecyclerView.Adapter<recyclerviewadapter.Viewholder> {
ArrayList<customitem> datalist;
vonclick mclick;
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerviewexdesign,parent,false);
return new Viewholder(v,mclick);
}
public recyclerviewadapter(ArrayList<customitem> datalist) {
this.datalist = datalist;
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
customitem n = datalist.get(position);
holder.productname.setText(n.getproductname());
}
#Override
public int getItemCount() {
return datalist.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView productname;
public Viewholder(#NonNull View itemView, final vonclick listener) {
super(itemView);
productname = itemView.findViewById(R.id.titleid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener!=null){
int possition =getAdapterPosition();
if (possition !=RecyclerView.NO_POSITION){
listener.cclick(possition);
}
}
}
});
}
}
public interface vonclick{
void cclick(int possition);
}
public void recyclerviewonclicl(vonclick possition){
mclick=possition;
}
}
and item class:
public class customitem {
String productname,size,price,box;
int kg;
public customitem(){
}
public customitem(String productname, String size,String price,String box,int kg) {
this.productname = productname;
this.size = size;
this.price = price;
this.box = box;
this.kg = kg;
}
public String getproductname() {
return productname;
}
public void setproductname(String productname) {
this.productname = productname;
}
public String getsize() {
return size;
}
public void setsize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getBox() {
return box;
}
public void setBox(String box) {
this.box = box;
}
public int getKg() {
return kg;
}
public void setKg(int kg) {
this.kg = kg;
}
}
last one main class:
public class addproduct extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<customitem> datalist =new ArrayList<customitem>();
FirebaseDatabase mdatabase;
DatabaseReference mreference;
EditText productname,price,size,b2;
Spinner sizespinner;
Button okbutton;
View mview;
ImageView cancel;
AlertDialog d;
AlertDialog.Builder alert;
recyclerviewadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addproduct);
getSupportActionBar().setTitle("Add product");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mdatabase = FirebaseDatabase.getInstance();
//?????????????????????? my firebase referance ????????????
mreference = mdatabase.getReference().child("product");
mreference.keepSynced(true);
recyclerView = findViewById(R.id.recyclerviewid);
buildrecyclerview();
//mreference.child("product").setValue(datalist);
}
public void buildrecyclerview(){
adapter = new recyclerviewadapter(datalist);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.setAdapter(adapter);
mreference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
customitem j =dataSnapshot1.getValue(customitem.class);
datalist.add(j);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
adapter.recyclerviewonclicl(new recyclerviewadapter.vonclick() {
#Override
public void cclick(final int possition) {
//?????????????? alert dilog two for delete and update data ????????????????
AlertDialog.Builder bl = new AlertDialog.Builder(addproduct.this);
View v = getLayoutInflater().inflate(R.layout.manageralertdilogtwo,null);
bl.setView(v);
d=bl.create();
d.show();
final EditText productname2 = v.findViewById(R.id.productname2);
final EditText size2 = v.findViewById(R.id.packsizeid2);
final EditText price2 = v.findViewById(R.id.priceid2);
final EditText box2 = v.findViewById(R.id.Box2);
Button okbtn = v.findViewById(R.id.okbuttonid2);
Button dltbtn = v.findViewById(R.id.deleteid);
ImageView cross =v.findViewById(R.id.cancelid2);
final Spinner sp =v.findViewById(R.id.spinnerid2);
//String pn = datalist.get(possition).getproductname();
productname2.setText(datalist.get(possition).getproductname());
size2.setText(datalist.get(possition).getsize());
price2.setText(datalist.get(possition).getPrice());
box2.setText(datalist.get(possition).getBox());
sp.setSelection(datalist.get(possition).getKg());
cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//?????????????? update data accroding user selectiong ??????????????
//datalist.get(possition).setproductname(productname2.getText().toString());
//datalist.get(possition).setPrice(price2.getText().toString());
//datalist.get(possition).setsize(size2.getText().toString());
//datalist.get(possition).setBox(box2.getText().toString());
//datalist.get(possition).setKg(sp.getSelectedItemPosition());
customitem m = new customitem(productname2.getText().toString(),size2.getText().toString()
,price2.getText().toString(),box2.getText().toString(),sp.getSelectedItemPosition());
mreference.child(String.valueOf(datalist.get(possition))).setValue(m);
d.dismiss();
}
});
dltbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//???????????????? delete data from recycler view accroding user selection ???????????
//datalist.remove(possition);
mreference.child(String.valueOf(datalist.get(possition))).removeValue();
// adapter.notifyDataSetChanged();
d.dismiss();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.addproductmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.addproduct:
buildalert();
break;
case R.id.seedetails:
Intent n = new Intent(addproduct.this,managermain.class);
startActivity(n);
break;
}
return super.onOptionsItemSelected(item);
}
public void buildalert(){
//?????? alert dilog one for take data ???????????????
alert = new AlertDialog.Builder(addproduct.this);
mview = getLayoutInflater().inflate(R.layout.manageralertalertdilog,null);
productname = mview.findViewById(R.id.productname);
price = mview.findViewById(R.id.priceid);
alert.setCancelable(true);
size = mview.findViewById(R.id.packsizeid);
cancel = mview.findViewById(R.id.cancelid);
sizespinner = mview.findViewById(R.id.spinnerid);
okbutton = mview.findViewById(R.id.okbuttonid);
b2 = mview.findViewById(R.id.Box);
alert.setView(mview);
final AlertDialog dl = alert.create();
dl.show();
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dl.dismiss();
}
});
okbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (productnamem() && sizem()){
//add data from alert dilog
String productnm = productname.getText().toString();
String pricec = price.getText().toString();
String sizee = size.getText().toString();
int kg = sizespinner.getSelectedItemPosition();
String box= b2.getText().toString();
//?? add data in recyclerview from alert dilog ???????????????
//datalist.add(new customitem(productnm,sizee,pricec,box,kg));
customitem n = new customitem(productnm,sizee,pricec,box,kg);
mreference.child(String.valueOf(datalist.size())).setValue(n);
//adapter.notifyDataSetChanged();
//mreference.setValue(datalist);
dl.dismiss();
}
}
});
}
public boolean productnamem(){
if (productname.getText().toString().trim().isEmpty()){
productname.setError("Please fill it");
productname.setFocusable(true);
return false;
}
else {
return true;
}
}
public boolean sizem(){
if (size.getText().toString().trim().isEmpty()){
size.setError("Please fill it");
size.setFocusable(true);
return false;
}
else {
return true;
}
}
}

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

Losing data when refresh RecyclerView

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?

Android Firebase - How to make query

I'm doing saving post feature now. I want display all saved post in one activity. I have made an activity where is RecyclerView in which I store all of posts and I have made made PostRow activity already. I have this databse:
. I want to get all post which user has saved and i dont know how to get them from database. I have made PostAdapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder>{
private List<Post> mPostList;
private boolean mProcessLike = false;
private String mSinglePostId;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
public PostAdapter (List<Post> postList, DatabaseReference databaseUsers, Context ctx){
this.mPostList = postList;
this.mDatabaseUsers = databaseUsers;
this.mCtx = ctx;
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
}
#Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row, parent, false);
PostViewHolder postViewHolder = new PostViewHolder(v);
return postViewHolder;
}
#Override
public void onBindViewHolder(final PostAdapter.PostViewHolder holder, int position) {
Post post = mPostList.get(position);
holder.setTitle(post.getTitle());
holder.setImage(post.getImage());
holder.setPostId(post.getPostId());
holder.setLikeButton(holder.getPostId());
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent postSingle = new Intent(mCtx, SinglePostActivity.class);
postSingle.putExtra("postId", holder.getPostId());
mCtx.startActivity(postSingle);
}
});
holder.getLikeBtn().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike){
if(dataSnapshot.child("saved").hasChild(holder.getPostId())){
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.removeValue();
mProcessLike = false;
}else {
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.setValue("saved");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return mPostList.size();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
private TextView mPostTitle;
private ImageView mPostImage;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
private ImageButton mLikeBtn;
private String postId;
private View mView;
public PostViewHolder(View itemView) {
super(itemView);
this.mPostTitle = (TextView) itemView.findViewById(R.id.post_title);
this.mPostImage = (ImageView) itemView.findViewById(R.id.post_image);
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
this.mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
this.mLikeBtn = (ImageButton) itemView.findViewById(R.id.like_btn);
this.mCtx = itemView.getContext();
this.mView = itemView;
}
public void setTitle(String title){
mPostTitle.setText(title);
}
public void setImage(String image){
Picasso.with(mCtx).load(image).into(mPostImage);
}
public void setPostId(String id){
this.postId = id;
}
public String getPostId(){
return this.postId;
}
public void setLikeButton(final String postKey) {
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("saved").hasChild(postKey)){
mLikeBtn.setImageResource(R.drawable.ic_favorite_pink_48dp);
}else{
mLikeBtn.setImageResource(R.drawable.ic_favorite_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public ImageButton getLikeBtn() {
return this.mLikeBtn;
}
public View getView() {
return this.mView;
}
}
}
I recommend changing your database structure, more specifically on the books node, to something like this:
{
"books":{
"2ExF2vKltibqCbE0oVOEHkYSRi2":{ /* the user key*/
/*list of books saved by that user*/
"-L2L2UgB...":{
"title":"Title goes here"
},
"-anotherBookKey":{
"title":"Title goes here"
}
},
"anotherUserKey":{
"hisSavedBookKey":{
"title":"Title goes here"
}
}
},
"users" : {
"2ExF2vKltibqCbE0oVOEHkYSRi2" : {
"image" : "...",
"name" : "Karol546",
"saved" : {
"-L2L2UgB...":"saved"
},
"thumb_image" : "default"
},
}
}
And when you want to list all books saved by the user 2ExF2vKltibqCbE0oVOEHkYSRi2, you'd use this DatabaseReference:
String userId = "2ExF2vKltibqCbE0oVOEHkYSRi2";
DatabaseReference savedRef = FirebaseDatabase.getInstance()
.getReference().child("books").child(userId);

Categories