How to get data from fields, not entire document. Firestore [duplicate] - android

This question already has answers here:
How to access a specific field from Cloud FireStore Firebase in Swift
(5 answers)
Closed 3 years ago.
I am trying to get data from fields on my firebase firestore, but not the whole document.
Fields that i want
Here is my code that get the whole document.
db.collection("Reminder").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
dbReminder p = d.toObject(dbReminder.class);
p.setId(d.getId());
remtasklist.add(p);
}
adapter.notifyDataSetChanged();
}
}
});
Thanks in advance.
Edit: I updated with the collection pic.
Collection

You can get specific fields from the documentSnapshot.
String location = documentSnapshot.getString("inLocation");
String time = documentSnapshot.getString("time");//assuming time here is string
String title = documentSnapshot.getString("title");

Related

Firestore to query Array sub collection

I have my firestore collection structure as shown in the image.
Following is the main collection name which contains currently logged userId as a document ("AuScbj..")
which contains a subcollection called uIds which contains the user ids of users he follows.
When logged in user ("AuScbj..") visits a particular user profile, how can I check whether that profile user's Id available in his following list just by querying like below
firebaseFirestore.collection("Following)
.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.collection("uIds").where(
You're looking for .where(fieldPath: "uids", opStr: "array-contains", value: followingUID). It should work with your simple "array" data.
To check if id1 is present inside the uIds array in a really simpler manner, first, you should create a class:
class Document {
List<String> uIds;
}
Then get the "AUScbTj5MpNY.." document and read the content of the uIds array using the following method:
private void checkId(String id) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference followingRef = rootRef.collection("Following");
DocumentReference uidRef = followingRef.document(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<String> uIds = document.toObject(Document.class).uIds;
if (uIds.contains(id)) {
//Update the UI
}
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
Inside the onComplete, we get the array as a List and check if the id with which we are calling the method, exists inside the array. To make it work, kick it off with:
checkId(id1);
Please also note that:
firebaseFirestore.collection("Following)
.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.collection("uIds").where(/* ... /*);
Will never work, as uIds is an array inside a document and not a collection.
You can also find more info, in the following article:
How to map an array of objects from Cloud Firestore to a List of objects?

Android ignore Case sensitive with Firebase whereEqualTo [duplicate]

This question already has answers here:
Cloud Firestore Case Insensitive Sorting Using Query
(3 answers)
Closed 4 years ago.
db.collection("UserInformation").whereEqualTo("userName" , searchEditText.getText().toString())
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(final QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty())
{
}else
{
List<UserModel> listUsers = documentSnapshots.toObjects(UserModel.class);
final SearchUserListAdapter adapter = new SearchUserListAdapter(getBaseContext() , listUsers);
searchLista.setAdapter(adapter);
}
}
});
i need to ignore case sensitive and find the "nickname" however i typed the nickname with capital or small letters or both i tried to add startAt() or endAt() and i didn't worked for me and the all answers talk about to save the nickname with upper and lower case but it is not good logic to me
I think there is no support for lowercase searches in Firebase. An idea to handle this would be to store the lowercase string along side the original string and then query the lowercase string instead.

Android Firestore query get the id of the document that contains the value in the search

Firestore database image
Hello, I just tried to use Firestore. I had some problem when getting document id.
The question is, I want to get a document id (red box) which has value (blue box) in it.
I use the following query:
collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")
But did not give results.
Thanks!
As in the official documentation:
Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.
So there is no way in which you can use the following query:
collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")
If you only want to get the entire userId array you need to iterate over a Map like this:
collection("mychannel").document("1fReXb8pgQvJzFdzpkSy").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("userId")) {
Log.d("TAG", entry.getValue().toString());
}
}
}
}
}
});
But note, even if userId object is stored in the database as an array, entry.getValue() returns an ArrayList, not an array.
So the output will be:
[74wRU4xHrcV9oWAXEkKeRNp41c53]
A better approach will be if you consider this alternative database structure, where each user id is the key in a map and all values are true:
userId: {
"74wRU4xHrcV9oWAXEkKeRNp41c53": true,
"AdwF...": true,
"YsHs...": true
}
This question is answered here: Firestore: Query by item in array of document
In summary, don't use arrays to store data in Firestore as the query you are trying to do is not available yet (remember it is still in beta). You should use a Map instead.

How to apply multiple query in android firebase? [duplicate]

This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 6 years ago.
This is My Firebase database structure
i want to get data like
category = "cat" and level = "1"
Here is my code
Query query = firebaseReference.orderByChild("category").equalTo("cat1").limitToFirst(20);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UTILS.Log.e(TAG, "List Of User Count " + dataSnapshot.getChildrenCount());
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
//FCreateUSer modelRegister = dataSnapshot1.getValue(FCreateUSer.class);
UTILS.Log.e(TAG, "User Email :" + dataSnapshot1.child("question").getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
it's wrok but how to use two condition in firbase i try two orderByChild but it's give error java.lang.IllegalArgumentException: You can't combine multiple orderBy calls!
Take a look at this video (it's in JavaScript, but it exactly solves your problem): https://youtu.be/sKFLI5FOOHs?t=612
Basically, you need to structure your data for your queries. In OP example Question will have field like category_level: "cat_1". Then you can perform query equalTo("cat_1"). You can leave out both category and level fields if you need it for other queries (but you will need to handle duplication in that case).
If you know that your number of items is small, simplest solution is to just pull all category=cat and filter level=1 items.

Retrieving data in alphabetical order using Firebase in Android Studio [duplicate]

This question already has answers here:
How can I sort an ArrayList of Strings in Java?
(5 answers)
Closed 7 years ago.
This question is a follow up question from a previous post.
Is there anyway to order the results alphabetically? I'm looking for something like Query's orderByValue().
...
protected ArrayList<String> usernames = new ArrayList<>();
Firebase userRef = ref.child("users");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
usernames.clear(); // Clear list before updating
for (DataSnapshot child : dataSnapshot.getChildren()) {
String username = (String) child.child("username").getValue();
usernames.add(username);
Log.v(TAG, usernames + "");
}
...
I believe you want Collections.sort(usernames) once you've read all of the children from the dataSnapshot.
How can I sort an ArrayList of Strings in Java?

Categories

Resources