Why does not array get updated on successful delete? - java

So I store a user with field called myMovies in firestore. I am able to successfully add a movie in this array but when I try to remove one it does not work and the logic behind the adding and removing is similar.
It does show me that the array is successfully updated but in firestore the element I delete is still there.
Here is my code:
#Override
public void removeMovie(Movie movie, FirebaseAddMovieListener listener) {
firebaseFirestore.collection("users").document(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).update("myMovies", FieldValue.arrayRemove(movie))
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
listener.onSuccess("SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onFailure(e.getMessage() + e + e.getLocalizedMessage());
}
});
}
Add Movie
#Override
public void addMovieToUserLibrary(Movie movie, FirebaseAddMovieListener
listener) {
firebaseFirestore.collection("users").document(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).update("myMovies", FieldValue.arrayUnion(movie))
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
listener.onSuccess("SUCCESS");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onFailure(e.getMessage() + e + e.getLocalizedMessage());
}
});
}
Database Structure

Related

How to get the firebase firestore document id

I am working on an application where i have list of items in recyclerview now on the recyclerview i have a heart icon when someone click on that icon that particular data added to the firebase and when again clikc on that data delete from the firebase now data is adding successully but i dont know why the data is not deleting from the firebase. please guide me
code is
holder.wishlist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int id = holder.getBindingAdapterPosition();
//CODE TO ADD THE ITEM TO THE WISHLIST
if(compoundButton.isChecked())
{
firebaseFirestore.collection("wishlistDetails").document(uid).set(wishMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(context, "added to firestire", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Toast.makeText(context, "item added to wishlist" + id , Toast.LENGTH_SHORT).show();
}else {
//CODE TO REMOVE THE WISHLIST FROM FIREBASE
firebaseFirestore.collection("wishlistDetails").document(datalist.get(position).getID())
.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
Try this -
In your wishlistmap add one more key id -- pass value uid for that key. Modify your wishlist model and add the id key.
Modify function for remove wishlist like below -
//CODE TO REMOVE THE WISHLIST FROM FIREBASE
firebaseFirestore.collection("wishlistDetails").document(list.get(position).getId())
.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Selecting in RecyclerView and delete from firebase in java

I want to delete my document from firebase. But first I need to determine the document id. I tried to get document id:
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
Then, I just wanted to delete my document. But firebase works async so code doesnt work in 'if' statement. When we first click the button, docId variable is null or it takes the docId which was clicked before till the async code part done.
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
}
}
});
System.out.println(docId);
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
notifyDataSetChanged();
}
});
You should structure your code so that any logic that depends on your asynchronous operation is executed or triggered within the response callback.
You can do something like this:
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
// The asynchronous operation has successfully completed
// and returned a value to our 'onSuccess()' callback.
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
System.out.println(docId);
// We can now use the value of docId.
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
// (1)
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
// I'm not sure how your RecyclerView is set up
// but I'm guessing you might want to move this call
// to 'notifyDataSetChanged()' to the section marked (1)
notifyDataSetChanged();
}
}
});
}
});
}

Why are no documents being returned?

I have this error when attempting to write to Firestore Database and I am at a loss. This is happening because documentReference.getDocuments() is empty but I expect it to be non-empty.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.uni.strengthprogression.data.FirebaseManager$9.onSuccess(FirebaseManager.java:120)
at com.uni.strengthprogression.data.FirebaseManager$9.onSuccess(FirebaseManager.java:117)
Line 117:
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
Line 120:
String id = documentReference.getDocuments().get(0).getId();
Full method:
public static void addBenchSession(String userEmail, Session session, BackGroundTaskOperation backGroundTaskOperation) {
db.collection("users").whereEqualTo("email", userEmail).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentReference) {
String id = documentReference.getDocuments().get(0).getId();
db.collection("users")
.document(id)
.update("bench_sessions", FieldValue.arrayUnion(session.toMap()))
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Successfully added document");
backGroundTaskOperation.onSuccess(null);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
Andreas and Alex were correct... userEmail was null as I hadn't correctly utilized putExtra() and getExtra().

How to Subtract two different node child values in Firebase Realtime Databse?

I'm creating a Food ordering app.for that I'm saving the food names into the Food unique ID. So I created Item Details as a node, in this node has shopuniqueID as a child node, in this node has food uniqueID
this ID contains food details such as discount,itemname,price,discount If the User book the foods, which will be saved as below format
, If the customer confirms the food order after that user-selected quantity wants to delete from total item quantity, How can I delete two different values which are in the two different nodes?
This is my tried coding
btnorder=findViewById(R.id.qrbillid);
databaseReference= FirebaseDatabase.getInstance().getReference("User Booking").child(UserID).child(shopid);
dbrefcheck=FirebaseDatabase.getInstance().getReference("Item Details").child(shopid);
btnorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
SelectedItems ui=dataSnapshot1.getValue(SelectedItems.class);
final String itemid=ui.getItemid();
final String Stritemselectedqty=ui.getItemid();
final String name=ui.getItemname();
///////////////////----find the user selection----////////////////////
dbrefcheck.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot2:dataSnapshot.getChildren())
{
UploadItem uploadItem=dataSnapshot2.getValue(UploadItem.class);
String uploadItemID=uploadItem.getKey();
String StrTotalqty=uploadItem.getQuantity();
if(itemid.equals(uploadItemID))
{
// do the mathematical operation
int totalqty=Integer.valueOf(StrTotalqty);
int selectedqty=Integer.valueOf(Stritemselectedqty);
int finalquality=totalqty-selectedqty;
Toast.makeText(MyBookedItems.this, ""+name+" ", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
///////////////////----find the user selection----////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
If We want to do mathematical operations between two node child values, We can't directly do that in Firebase Realtime Database.
Retrieve the value from the Firebase
after that do the modification and again upload it.
private void updateQuantity(final String itemid, final String selecteditem) {
Query query4 = dbrefcheck
.orderByChild("key") //key
.equalTo(itemid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String qty=ds.child("quantity").getValue(String.class);
int total=Integer.valueOf(qty);
int sub=Integer.valueOf(selecteditem);
int fv=total-sub;
String sfv=String.valueOf(fv);
Map<String, Object> map = new HashMap<>();
map.put("quantity", sfv);
dbrefcheck.child(itemid).updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
query4.addListenerForSingleValueEvent(valueEventListener);
}
private void moveSelectedItemstoOrder(final DatabaseReference fromPath, final DatabaseReference toPath) {
final String th=toPath.push().getKey();
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
toPath.child(th).setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
if (firebaseError != null) {
Toast.makeText(MyBookedItems.this, "Try again", Toast.LENGTH_SHORT).show();
} else {
StoreBookingDetails(th);
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void DeleteValuefromSelectedItems() {
databaseReference.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
private void StoreBookingDetails(final String keytostore) {
//////////////////------------retrive data-------------//////////////////////////////some these methods are unnecessary but i remove some code
savedata(keytostore);
//////////////////------------retrive data-------------//////////////////////////////
}
private void savedata(String keytostore) {
String status="Order Request";
// shopid ---->
BookingDetails bd=new BookingDetails(keytostore,currentdate,UserID,subtotal,status,f1,f2,f3,currentTime);
dbbookingDetails.child(keytostore).setValue(bd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
DeleteValuefromSelectedItems();
}else
{
Toast.makeText(MyBookedItems.this, "Check the intenet connection", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
/////////////////////////////--------------------/////////////////////////////////
UserBookingDetails ubd=new UserBookingDetails(shopname,shopid,shopphnno,keytostore,UserID,subtotal,currentdate,currentTime,"Order Sent","","");
dbbookingdetailsUser.child(keytostore).setValue(ubd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
AlertDialog.Builder adb = new AlertDialog.Builder(MyBookedItems.this);
adb.setTitle("Booking Successful");
adb.setPositiveButton("View History", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(MyBookedItems.this,OrderHistory.class));
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});

Not able to file the record in the Firestore database

I am trying to create a new document , and it is not giving me error in the logcat, but it is not even creating it.
I checked the address and retrieved the required values , they are all correct.
Please let me know where I am wrong in the below code.
db.collection("posts").document(postId).collection("comments").document(commentId).collection("messageRoom").document(roomId).collection("messages")
.add(chat)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
successCallback.onSuccess(documentReference);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
failureCallback.onFailure(e);
}
});

Categories