How to delete from Firebase Realtime Database using key? - java

I'm currently working on a project and I need to be able to delete from a database I've already created. I created it using the .push() to the database hence a unique key is created and thus needed for delete operations.
I tried using the answer from Frank Van Puffelen here How to delete from firebase realtime database?, but I ran into a bug where if two nodes have the same title they'll be deleted.enter image description here
The image shows how my Firebase database looks:
A bit of assistance or direction to an answer would go a long way. Thanks

If you want to delete a single element from your database, you need to know the path to that element, which includes also that pushed key. Your reference should look like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.child("-KlSNx87aYigsH3lLp0D");
keyRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "Element removed successfully!");
}
}
});
Otherwise, you can use a query that looks exactly like this:
Query idQuery = rootRef.orderByChild("id").equalTo(1);
In this case, Frank Van Puffelen's answer from the following post:
How to delete from firebase realtime database?
Will work perfectly fine.

Related

I want it to search anywhere between the text in firebase database [duplicate]

This question already has answers here:
Firebase "like" search on string [duplicate]
(1 answer)
How to perform sql "LIKE" operation on firebase?
(5 answers)
Closed 18 days ago.
This is my code to search in the firebase database but it only searches from the start not in between.
private void processSearch(String query) {
Query query1 = databaseReference.child("posts").orderByChild("bookName").startAt(query).endAt(query+"\uf8ff");
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
AllPostItemHelper itemHelper = dataSnapshot.getValue(AllPostItemHelper.class);
itemHelper.setPostId(dataSnapshot.getKey());
allPostItemSearch.add(itemHelper);
}
AllPostItemAdapter allPostItemAdapter = new AllPostItemAdapter(allPostItemSearch,getContext());
postThings.setAdapter(allPostItemAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
only search from the starting not in between
That's expected behavior since you are performing a call to Query#startAt() which:
Creates a query constrained to only return child nodes with a value greater than or equal to the given value, using the given orderBy directive or priority as default.
However, if you need to search for a substring, please note that this is not possible. You can only perform queries that match a string that starts with a specific string or starts with a range of strings.
If you think to download an entire node to search for fields client-side, please note that this solution isn't practical at all. To enable a full-text search for your Firebase Realtime Database data, I recommend you use a third-party search service like Algolia or Elasticsearch.
If you consider at some point in time to try using Cloud Firestore, please see the following example:
Is it possible to use Algolia query in FirestoreRecyclerOptions?
To see how it works with Cloud Firestore but in the same way, you can use it with Firebase Realtime Database.

How can I change multiple documents

How can I change multiple documents? I have 2 collections firestore. One (users) is for user account (email, name, etc).
To second collections (dashboard) users can add some message to a board. In this second collection is name, category, time etc.
What I want to do is when someone change his name or faculty in account, it will also change in second collection for each his comment so it will show up to date information
DocumentReference documentReference = fStore.collection("users").document(user.getUid());
Map<String, Object> edited = new HashMap<>();
edited.put("email",email);
edited.put("smallName",StringUtils.unaccent(profileName.getText().toString()).toLowerCase());
edited.put("fullName",profileName.getText().toString());
edited.put("fakulta",mySpinner.getSelectedItem().toString());
documentReference.update(edited).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditProfile.this, "Profile data are changed", Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
Firestore
Is there any way to do it without changing the whole structure of my app?
To update the user names in the comment docs, you'll need to:
Query the collection to find the comments by the user who updated their name. If you stored the UID for each user in the comment document, this would look something like fStore.collection("dashboard").where("uid", "==", "theUidOfTheUserWhoUpdatedTheirName"). If you didn't store their UID, you'll have to query on the old value of their name instead, but the code will be similar.
Loop over the query results and update each document in turn. If you have a lot of these, you may want to read about the fastest way to do this here: What is the fastest way to write a lot of documents to Firestore?

Delete map from subcollection Firestore/Android

I'm doing an Android project with Firestore database in it.
I'm having trouble trying to delete a subcollection map at it, can anyone help?
Image of the subcollection
I want to delete this whole red block. This is my method:
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("roteiros").document(collectionId)
.collection("eventos").document(subcollectionId)
.delete()
.addOnSuccessListener(successListener)
.addOnCompleteListener(completeListener)
.addOnFailureListener(failureListener);
This method is returning with success, but don't actually delete the doc.
I've already allowed all permissions in the database rules and tested on the simulator with the document path.
You can use the FieldValue.delete()
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("roteiros").document(collectionId)
.collection("eventos").document(subcollectionId)
.update("eventos", FieldValue.delete());
NOTE: You cant delete a specific index in an array. you can only delete the whole array and recreate it with another set of data.

How to search through a nodes children to see if a given value is present

I want to see if a value is in my firebase database, the user will provide the value thereafter I want to say if the value is present then move to the next activity.
Data in firebase is retrieved by adding a asynchronous listener to a database reference. So you have to change the way you are used to retrieve data from other data sources like MySQL...
Thus, define the reference to the part of firebase database where the user is going to insert its data and attach listener to it. In the listener write your code to go to the next activity.
For example:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/NodeOfTheUser");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//your code to go to the next activity
}
});
For more info: firebase documentation.

Android Studio how to get id from push of Firebase

I've done this push:
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.child(TipoAnuncio).push().setValue(fichaPet);
(Where fichaPet is a ad's class which is pushed in other object from firebase database)
My BBDD:
Users Firebase Database
I wanna get push's ID to write inside Ads from Users of FirebaseDatabase, and do something like this:
mDatabaseReference.child("Usuarios").child(userId).child("Ads").push().setValue(mDatabaseReference.child("Usuarios").child(userId).child("Ads").push().getKey());
but it doesn't get previously ID from previously ad published.
Thanks!!! :)
To solve this, please use the following code:
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference tipoAnuncioRef = mDatabaseReference.child(TipoAnuncio);
String key = tipoAnuncioRef.push().getKey(); //This is the value of your key
tipoAnuncioRef.child(key).setValue(fichaPet);
If you are using the push() methid again, a new id will be generated and there is no need for that.

Categories

Resources