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();
}
});
Related
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();
}
}
});
}
});
}
realtime Database in firebase doesn't save data and doesn't show any errors
i have already set
"rules": {
".read": "true",
".write": "true"
}
and this is the function it create new user and it's created in firebase but the user name and email doesn't save in realtime database
public void createUser(String email, String password, String userName) {
auth = FirebaseAuth.getInstance();
auth.createUserWithEmailAndPassword(email, password).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "user created", Toast.LENGTH_SHORT).show();
User user = new User(email, userName);
FirebaseDatabase.getInstance().getReference().child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "user info added", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
and this line is appere as toast i don't know how it is happen
Toast.makeText(getContext(), "user info added", Toast.LENGTH_SHORT).show()
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().
i have a favorite feature in my application. when a user clicks on the favorite button to favorite a certain shop or item, the image of the heart goes from outlined to inlined, similar to the way the like button works in Instagram.
Now it works fine and changes when i click it and everything, but when i move to another page or close down the application, it wont remember that this is a saved item or shop.
how can i save the ImageView after it is clicked, and someone moves to another activity or closes the app?
full code:
details_fave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Task<QuerySnapshot> f = fStore.collection("Favorites")
.whereEqualTo("shopPID", SID).whereEqualTo("usersID", UID)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
if (querySnapshot.isEmpty()) {
details_fave.setImageResource(R.drawable.ic_baseline_favorite_24);
clicked = !clicked;
Map<String, Object> fav = new HashMap<>();
fStore.collection("Favorites").add(fav).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(DetailsActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(DetailsActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}else {
for (QueryDocumentSnapshot document : task.getResult()) {
document.getReference().delete();
Toast.makeText(DetailsActivity.this, "Deleted", Toast.LENGTH_SHORT).show();
}
details_fave.setImageResource(R.drawable.ic_outline_favorite_border_o);
}
}
}
});
}
});
my code favorite image code:
details_fave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (querySnapshot.isEmpty()) {
details_fave.setImageResource(
R.drawable.ic_baseline_favorite_24
);
}else{
details_fave.setImageResource(
R.drawable.ic_outline_favorite_border_o
);
}
}
I am new to Firebase and I am facing a problem in delete an item from the recycler view I created. but I am unable to understand how to delete items using an auto-generated key. This is how I added item into the database:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("categories");
String key = reference.push().getKey();
reference.child(key).setValue(categoryData).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(add_category.this, "Category added", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(add_category.this, "Failed to add", Toast.LENGTH_SHORT).show();
}
});
As in your comment, if you want to delete, for example, the second item, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference secondChildRef = rootRef.child("categories").child("-M1qUEGi0u4rX5Ju59r4");
secondChildRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "Second item deleted!");
}
}
});
So to delete a particular item, you to know its ID so you can add it to the reference.