How do I insert data in firestore in array of string? - android

Here is want I want to do by code and insert in realtime
I Want to take userName from here and want to add in above, array of string userName_*
Create collection("room")
Add randomNumber to "room" Collection
getCurrentUser name ADD to array of users in firestore field
Keeps checking and update in recycler view if new user is found in room -> randomCode -> inRoom (userName)
I want to update the recycler view and show users only if code (randomNumber) generated from start activity (Host) matches with the join activity
Start activity
Join activity

You must use a combination Set with Merge:true to push id's to a document (create if not created) to get this result.
How you manage the document ID wasn't defined clearly, but I assume you have some internal logic, provided is an example of how to push a string into an array.
DocumentReference FirestoreRef = db.collection("room").document("myID");
Map<String, Object> map = new HashMap<>();
map.put("userList", FieldValue.arrayUnion("user_id"));
FirestoreRef.set(docRef, map, SetOptions.merge());

Related

How to get the document id which consists that collection while making collection group query?

I am making a collection group query and getting the data by .get method , is there any way to get the document id which consists that collection ?
Collection:Users ------ Doccument:user1 -> Collection:Posts -> Document:post 1,2,3..
------- Doccument:user2 -> Collection: Posts ->
Document:post a,b,c..
So while making the query i am getting post 1,2,3.. & a,b,c..
But how to get the document document id from where a,b,c or 1,2,3 are comming ?
In this case it i want to get user 1 & user 2 as result !
Just let me know if it is possible first !
Android : Kotlin
For a document of any of the Posts subcollections you need to:
Firstly, get the CollectionReference of the Document's parent Collection, with the getParent() method of the DocumentReference
Secondly, on this parent CollectionReference, call the getParent() method which returns the DocumentReference of the Collection's parent Document.
Finally, use the getId() method on this DocumentReference. You're done.

Firebase data insertion using child unique id

I am beginner in Android studio. I retrieved child key in android studio and now I want to insert one Column into this child without loosing existing data. I just want to insert data existing child.
How can I implement it?
It sound like you're looking for the updateChildren method, that allows you to update specific children under a path, without replacing the other children under that path.
If the object you want to add a new property too lives under pathToObject, you can add new values with:
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("newProperty1", "New value");
childUpdates.put("newProperty2", "New value");
DatabaseReference ref = FirebaseDatabase.getInstance.getReference(pathToObject);
ref.updateChildren(childUpdates);
If you only want to add/set a single property under the original path, you can also do that with:
ref.child("newProperty1").setValue("New value");
For more on this, see the documentation on updating specific fields.

Fetch SubCollection data into Recyclerview

I'm trying to retrieve data from a Firebase sub collection in a recyclerview. I think it must be possible but what I did was not right I think
I want to recover the data from REPARS_TABLE in Recyclerview
Android - Cloud Firestore
Query query = db.collection("RESTO_TABLE").document().collection("REPARS_TABLE").orderBy("nomRepars");
FirestoreRecyclerOptions<ReparsModele> OptionRepars = new FirestoreRecyclerOptions.Builder<ReparsModele>()
.setQuery(query,ReparsModele.class)
.build();
Log.d("SHOW","SHOW QUERY"+ query);
bureauReparsAdapter = new BureauReparsAdapter(OptionRepars);
repaLists.setHasFixedSize(true);
repaLists.setLayoutManager(new LinearLayoutManager(getContext()));
repaLists.setAdapter(bureauReparsAdapter);
bureauReparsAdapter.notifyDataSetChanged();
You will need to call out the ID of the document whose subcollection you want to you. Right now, you're calling document() with no parameters, which means it's generating a random ID as part of the path. You will need to instead pass it the ID of the document.
If you don't know the ID ahead of time, then you won't be able to do this query, or you will have to use a collection group query and filter the documents you want from all of the subcollections named "REPARS_TABLE".

Removing map elements from Google Cloud Firestore

I'm trying to remove a map<> from Google Cloud Firestore.
I use the following code for updating in Firestore
fun updateData(userId: String, values: Map<String, Any>) =
db.collection(COLLECTION_DATA).document(Id).update(values)
The document contains the used id's generated for google sign in and one of the field in the document is a map<Key,Value> . I'm trying to delete the content of the Field (removing a specific <key,value> pair)
I pass (userId, mapOf("FieldName.${Key}" to FieldValue.arrayRemove(Value))) as the parameter while calling the above firestore function.
But after updating the value in Firestore, the key is left out and the values are cleared.
If I pass (userId, mapOf("FieldName" to FieldValue.arrayRemove(Key))) as the parameter, then the whole map<> is removed (which is what I want) but the data structure of the Field is converted as an array after performing the update.
FieldValue.arrayRemove() is for array type fields only. It won't work here, because you're not actually using any arrays or lists.
You will just want to use FieldValue.delete() to remove the any map key and its value.
updateData(userId, mapOf("FieldName.${Key}" to FieldValue.delete()))

How to save data on top of the already saved data in Firebase?

I am saving some data in FirebaseDatabase under a child as a key:value pair.
The problem is that data is getting saved as pushed, like if data1 is saved already than data2 will get saved below it. I want to save it above this already saved data.
Here is the data structure:
- branch
- child
- uniqueKey1: data1
- uniqueKey2: data2
I am saving the data using this code:
String key = mDatabase.child("branch").child("child").push().getKey();
mDatabase.child("branch").child("child").child(key).setValue(data);
What I want is the structure below:
- branch
- child
- uniqueKey2: data2
- uniqueKey1: data1
How to save the newly added data above the already saved data? Please let me know.
In your firebase database, childs in a node are ordered in alphabetical order, no matter which order you save them.
If you want to retrieve them later in some specific order, let's say order by date added, you might want to create a timestamp reference.
Check here:
How to sort value inside a Firebase child to the rest?
Edit: a lot of answers and edited questions while writing my answer, but as others mentioned you should not worry about the order you see the data in the database, you should only care to provide the right structure to retrieve the data correctly.
As I said, in the DB the childs are ordered in alphabetical order so if you insist on ordering it by date added you should figure out a way to update the key accordingly and then update the whole node.
I don't think the order in which you save data is important as long as you have a strategy to retrieve it correctly in your order of choice. Firebase provides API to retrieve data ordered by either key or value.
Work with Lists of Data on Android
If you just want to retrieve the record first which was added last, you can put a timestamp that accompanies your data. There are also methods that gets you last record of a collection.
What you are trying to do is update data1. Then what you have to do is,
Get reference of the node you want to update.
DatabaseReference ref = mDatabase.child("branch").child("child").child("data1");
then update the child node. I'm assuming there is a child name under data1, whose value is 'Foo'. And now you want to update it 'Bar'.
Hashmap<String, String> map = new Hashmap();
map.put("name","Bar");
ref.updateChildren(map);
This is how you update a node. If you want to completely replace the node, then you can delete the node and by calling removeValue() method and pushing the data again!.

Categories

Resources