RecyclerView item delete item but not deleting data in firebase - android

My problem is that when I click the delete button it deletes the item but not deleting the data in the database.
public class ViewHolderClass extends RecyclerView.ViewHolder {
TextView subjectName, day, time , subCounter;
ImageView delete;
public ViewHolderClass(#NonNull final View itemView) {
super(itemView);
subjectName=itemView.findViewById(R.id.subjectName);
day=itemView.findViewById(R.id.day);
time=itemView.findViewById(R.id.time);
delete = itemView.findViewById(R.id.deleteIcon);
subCounter = itemView.findViewById(R.id.subCounter);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
FetchRheinSubject clickedData = fetchDataList.get(pos);
fetchDataList.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, fetchDataList.size());
}
});
}
}

If you don't know the key of the items to remove, you will first need to query the database to determine those keys:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple");
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});

Related

How to update recyclerview from firebase realtime database for a chat app

I am using recyclerview and firebase realtime database together to allow user to send messages to other users.When a message is sent I need to start that activity again to reload the updates.Is there anyway to do this automatically so that when the user clicks on send the message is displayed directly.
Action when send button is clicked
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageBox.getText().toString();
if (message.equals("")){
Toast.makeText(privatemessageactivity.this, "You cant send an empty message", Toast.LENGTH_SHORT).show();
}else{
messagedref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()){
messagedref.setValue(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Map<String,Object> mymessage = new HashMap<>();
mymessage.put("Image",myImage);
mymessage.put("Message",message);
sendmessageref.push().setValue(mymessage);
}
}
});
Action to retrieve the data
sendmessageref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot snapshot1 : snapshot.getChildren()){
MessageClass ld = snapshot1.getValue(MessageClass.class);
list.add(ld);
}
adapter = new MessageAdapter(list);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
My adapter class and my ViewHolder class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder>{
private List<MessageClass> list;
public MessageAdapter(List<MessageClass> list) {
this.list = list;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.messagelayout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
MessageClass ld = list.get(position);
holder.message.setText(ld.getMessage());
if (!ld.getImage().equals("noimage")){
Glide.with(getApplicationContext()).load(ld.getImage()).into(holder.circleImageView);
}else{
Glide.with(getApplicationContext()).load(R.drawable.profile).into(holder.circleImageView);
}
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView message;
CircleImageView circleImageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
message = itemView.findViewById(R.id.messagesmessage);
circleImageView = itemView.findViewById(R.id.messagespp);
}
}
}
The whole purpose of using Firebase is that you don't have to explicitly reload the messages. If you use addValueEventListener instead of addListenerForSingleValueEvent, Firebase will keep listening for changes on the server, and will call your onDataChange again if there as any changes.
So a common way to keep your message list up to date is:
adapter = new MessageAdapter(list);
recyclerView.setAdapter(adapter);
sendmessageref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()){
MessageClass ld = snapshot1.getValue(MessageClass.class);
list.add(ld);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
The changes:
Uses addValueEventListener instead of addListenerForSingleValueEvent so that it gets called both for the initial data and when there are changes.
Create and assign the adapter outside of onDataChange, since you'll want to set the adapter only once, and then update its data.
Clear the list in onDataChange, since we'll now get called multiple times, and each time we get a full DataSnapshot of all the relevant data.
Notify the adapter of the new data, with adapter.notifyDataSetChanged() so that it can refresh the UI,.
Implement onCancelled, because it's a bad practice to ignore possible errors.

Why I am getting only the 1st and last adapter Position's Database ID Correctly?

I have set an intent from HomeFragment Card Click to redirect to Second Activity. Also, I am sending the current position's Database ID from the recyclerView Adapter.
But in the Second Activity, only the 1st and Last items ID are received correctly. If i click on 3rd position item, then some other position's ID is send to Second Activity.
Here is my Code :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<HomeModel> homeModelList;
DatabaseReference databaseReference;
List<String> keysList;
String keyID;
public HomeAdapter(Context context, List<HomeModel> homeModelList) {
this.context = context;
this.homeModelList = homeModelList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_news, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final HomeModel homeModel = homeModelList.get(position);
holder.timesAgo.setText(homeModel.getTimesAgo().trim());
holder.newsTitleTextView.setText(homeModel.getNewsTitle().trim());
holder.newsDetailTextView.setText(homeModel.getNewsDetail().trim());
Log.e("View counts ", String.valueOf(homeModel.getViewCounts()));
holder.view_counter.setText(String.valueOf(homeModel.getViewCounts()));
Glide.with(context).load(homeModel.getNewsImage()).centerCrop().into(holder.newsThumbnailImageView);//set error and placeholder
databaseReference = FirebaseDatabase.getInstance().getReference("News");
// final String z = databaseReference.child(String.valueOf(homeModelList.get(position))).getKey();
// Toast.makeText(context, z, Toast.LENGTH_SHORT).show();
keysList = new ArrayList<>();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
keysList.add(childSnapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pos = keysList.get(holder.getAdapterPosition());
Log.e("current Position is", pos);
Toast.makeText(context, keysList.get(position), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DetailNews.class);
intent.putExtra("currentPosition", pos);
context.startActivity(intent);
}
});
How can this Issue be Solved ? Please Guide me .
Change the following code:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
keysList.add(childSnapshot.getKey());
}
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pos = keysList.get(holder.getAdapterPosition());
Log.e("current Position is", pos);
Toast.makeText(context, keysList.get(position),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DetailNews.class);
intent.putExtra("currentPosition", pos);
context.startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to get data from a firebase table by using another table

So I'm trying get my orders listed as users first and then later when clicked taken to the place where all items can be seen. I have set the order ID as the user uid and now I'm trying to get the uid and from that fetch user data. The mykey i have defined as public in starting but I think I'm using it inside loop and hence can't access it outside. Please help
Code I'm trying
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Order");
firebaseDatabase.keepSynced(true);
firebaseDatabase2 = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseDatabase.keepSynced(true);
firebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mykey = snapshot.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseDatabase2.child(mykey), Users.class).build();
FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder>(options)
{
#Override
public Orders.UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_layout,parent,false);
return new Orders.UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(Orders.UsersViewHolder holder, int position, Users model) {
holder.setName(model.getName());
holder.setStatus(model.getMobile());
}
};
mylist.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
View mview;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name) {
TextView userNameView = mview.findViewById(R.id.username);
userNameView.setText(name);
}
public void setStatus(String status) {
TextView userStatusView = mview.findViewById(R.id.phone);
userStatusView.setText(status);
}
}

How to stop item trembling on recyclerview?

I have implemented a notification center using a
recyclerview displayed on a fragment , when I click on the item it writes a value on the database and then base of the condition the green Notification Bell appears/dissapears, the problem here is that all items get affected from trembling effect
Image:
https://im4.ezgif.com/tmp/ezgif-4-1adb4a5b29e3.gif
My adapter
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
NotifsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUserID).child("comments").child(delUid).hasChild("state"))
{
String state = dataSnapshot.child(currentUserID).child("comments").child(delUid).child("state").getValue().toString();
if (state.equals("unread"))
{
holder.notifImg.setVisibility(View.VISIBLE);
}
else {
holder.notifImg.setVisibility(View.GONE);
}}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ NotifsRef.child(currentUserID).child("comments").child(delUid).child("state").setValue("read");
}
});
}
#Override
public int getItemCount() {
return mNotifications.size();
}
Fragment:
{
OnCreate{...}
notificationList = (RecyclerView) notificationFragmentView.findViewById(R.id.notifications_list);
notificationAdapter = new NotificationAdapter(getContext(), mNotifications);
notificationList.setAdapter(notificationAdapter);
notificationList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
notificationList.setLayoutManager(linearLayoutManager);
}
private void readMsgList()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{ mNotifications.clear();
for (DataSnapshot snapshot : dataSnapshot.child(currentUserID).child("comments").getChildren())
{
Notifications notifications = snapshot.getValue(Notifications.class);
mNotifications.add(notifications);
}
notificationAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
}
I have tried to change the listener from ValueEventListener to SingleValueEventListener but without any result.
Is there any way to correct this ?

How to remove parent from firebase database from the recycler adapter?

I am doing a project in firebase database and wanted to delete a parent from the firebase database in a recycler view. This what it looks like from my firebase Database I want to delete this key that has an arrow.
Problem:- The code does not delete a parent key in the image. I want to delete the key with an arrow mark.
This is my code for the view-holder
public class ViewHolder1 extends RecyclerView.Adapter<ViewHolder1.ImageViewHolder> {
private Context mContext1;
private List<Model1> mModel1;
private ImageAdapter.OnItemClickListener mListener;
public ViewHolder1(Context context1, List<Model1> models1) {
mContext1 = context1;
mModel1 = models1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext1).inflate(R.layout.row1, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
final Model1 mModelcur = mModel1.get(i);
imageViewHolder.img_food.setText(mModelcur.getFood());
imageViewHolder.img_order.setText(mModelcur.getOrder());
imageViewHolder.img_cost.setText(mModelcur.getPrice());
}
#Override
public int getItemCount() {
return mModel1.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public TextView img_food;
public TextView img_order;
public TextView img_cost;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
img_food = itemView.findViewById(R.id.Foody);
img_order = itemView.findViewById(R.id.Ordery);
img_cost = itemView.findViewById(R.id.Costy);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(Menu.NONE, 1,1,"Delete");
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
switch(item.getItemId())
{
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener
{
void onItemClick(int position);
void onDeleteClick1(int position);
}
public void setOnItemClickListener(ImageAdapter.OnItemClickListener listener)
{
mListener = listener;
}
}
and this is for my mainactivity
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
final String myParentNode = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myParentNode).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
final String key = posts.getKey();
if(key.equals(myParentNode))
{
mDatabaseReference1 = FirebaseDatabase.getInstance().getReference(key).child("Ordered");
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Model1 model2=postSnapshot.getValue(Model1.class);
mModel2.add(model2);
}
mAdapter2.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
}
#Override
public void onDeleteClick1(int position) {
Model1 selectedItem = mModel2.get(position);
String selectedKey = selectedItem.getFood();
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
String myKey = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
String myKey = posts.getKey();
FirebaseDatabase.getInstance().getReference().child(myKey).child("Ordered").removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("Delete", "Notification has been deleted");
} else {
Log.d("Delete", "Notification couldn't be deleted");
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
mDatabaseReference1.removeEventListener(mDBListener);
}
Update Can someone help me, please? The code crash after I clicked a back button now. I really need help, please. I can't seem to delete the key or the child in the recycler adapter.

Categories

Resources