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.
Related
I am new to android studio and firebase. I am trying to save a list of people to firebase like this. Idea is that the logged in user should be able to save information about some people.
String userId = user.getCurrentUser().getUid();
databaseReference.child("users").child(userId).child("savedPersons").child("name").setValue(nameTxt);
databaseReference.child("users").child(userId).child("savedPersons").child("surname").setValue(surnameTxt);
databaseReference.child("users").child(userId).child("savedPersons").child("gender").setValue(genderTxt);
databaseReference.child("users").child(userId).child("savedPersons").child("ageTxt").setValue(ageTxt);
It does not surprise me that it deletes the previous saved person when i save another one but i don't know how to save all of them. I have this in my firebase but i need multiple saved users. How do i do it ?
Firebase screenshot
If you want to save multiple people in a list in the database, you'll want to call push:
String userId = user.getCurrentUser().getUid();
DatabaseReference newRef = databaseReference.child("users").child(userId).child("savedPersons").push(); // 👈
newRef.child("name").setValue(nameTxt);
newRef.child("surname").setValue(surnameTxt);
newRef.child("gender").setValue(genderTxt);
newRef.child("ageTxt").setValue(ageTxt);
This will create a new child node under savedPersons each time you call push(). To learn more on this, see the Firebase documentation on appending data to a list.
Note that calling setValue for each property is wasteful, and may lead to unexpected behavior down the line. I recommend putting all values in a map, and then adding them all with one call to setValue:
Map<String, Object> values = new Map<>();
values.put("name", nameTxt);
values.put("surname", surnameTxt);
values.put("gender", genderTxt);
values.put("ageTxt", ageTxt);
newRef.setValue(values);
I am facing issues with my RecyclerView in displaying my app's candidates when I include the added map field in my query. I also have created an index for this query but still, nothing comes out of my RecyclerView.
This is the UPDATED query code. If there is something wrong with the coding, please do notify me.
FirebaseUser user = mAuth.getCurrentUser();
String voterID = user.getUid();
Query query = notebookRef.whereEqualTo("registrationStatus", "Accepted").whereEqualTo( voterID, false).orderBy("candidateFullName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<VoterCandidateItem> options = new FirestoreRecyclerOptions.Builder<VoterCandidateItem>()
.setQuery(query, VoterCandidateItem.class)
.build();
adapter = new VoterCandidateAdapter(options);
recyclerView = findViewById(R.id.candidateList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
recyclerView.setItemAnimator(null);
This is the UPDATED screenshot of Firestore DB:
And this is the UPDATED screenshot of the index:
The following query:
Query query = notebookRef
.whereEqualTo("registrationStatus", "Accepted")
.whereEqualTo(voterID, false)
.orderBy("candidateFullName", Query.Direction.ASCENDING);
Requires an index, otherwise, it will not work. If you are using Android Studio, you'll find in the logcat an error message that looks like this:
FAILED_PRECONDITION: The query requires an index. You can create it here: https://console.firebase.google.com/v1/r/project/...
The required query can be created either directly in the Firebase Console, or by clicking on that link. If the click doesn't work, simply copy and paste the URL into a web browser and your index will be created automatically for you.
If you choose the console, remember to set:
Collection: Candidates
Fields: registrationStatus ascending and voterID: ascending
I'm developing an Android app and I need to make a complex query on my Firestore database and create a FirestoreRecyclerAdapter. To create the adpater I need a FirestoreRecyclerOptions object that take in input the whole query. Reading the documentation, I can't use in my query the methods whereGreaterThan, whereLessThan, oderBy, etc, on different parameters. For example, how can I get users from db who have age greater than/less than AND who have weight greater than/less than?
For example the document's structure in my firestore database is:
Users --->UserID--->userName(String)
--->userAge(number)
--->userHeight(number)
--->userWeight(number)
FirebaseFirestore db;
db = FirebaseFirestore.getInstance();
RecyclerView recyclerView;
recyclerView = (RecyclerView)findViewById(R.id.recyclerViewID);
.
.
.
Query query = db.collection("Users").//the complex query that i need
FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
adapter = new UsersAdapter(options, this);//get in input options and the context
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
Edit: A possible solution in my last comment to answer 1
There are some query limitations when it comes to Firestore:
Query limitations
Cloud Firestore does not support the following types of queries:
Queries with range filters on different fields, as described in the previous section.
So you cannot query your database on range filters using whereGreaterThan() and whereLessThan() methods on different properties and pass it to an adapter.
Edit:
A possible solution for this issue would be to filter your records client side twice. First query the database using the first property and second using the second property. Unfortunately you cannot achieve this in a single go.
Edit2:
The solution would be to query the database using the first query, get the corresponding elements, query the database again using the second query and get the corresponding elements and then merge the results client side. Now the elements from the database were filtered twice. Pass a list of that elements to an adapter and that's it. Note, when using this solution you cannot use the Firebase-UI library anymore but this how you can get your items filtered twice.
I had a Firestore collection named "Users" and Documents of user names , and an integer field of every username , now i wanna compare all those fields and put the biggest one on the top of the list and so on till 10 items , thanks .
Assuming that you have the users of your app added as documents within the Users collection and the name of the property is score, to achieve this, please use the following code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Users")
.orderBy("score", Query.Direction.DESCENDING)
.limit(10);
I have the following Firebase database structure, and I would like to retrieve the entire object that has a host of "Mike 22".
This is not in a ValueEventListener event, so I don't have access to the DataSnapshot. How can I retrieve the object based on that query? I want to do it in an SQL style where you'd type SELECT object FROM objects WHERE host = "Mike 22". Is there any way to do this?
Currently I have the reference to the database as seen below:
mDatabase = FirebaseDatabase.getInstance().getReference().child("objects");
This is covered in Sorting and filtering data in the Android Guide. Use orderByChild and equalTo:
mDatabase = FirebaseDatabase.getInstance().getReference().child("objects").orderByChild("host").equalTo("Mike 22");