Android ignore Case sensitive with Firebase whereEqualTo [duplicate] - android

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.

Related

How to only read data from database when the document is added or deleted [duplicate]

This question already has answers here:
How to skip initial data and trigger only new updates in Firestore Firebase?
(4 answers)
Closed 2 years ago.
i have a problem with my code. I want only to listen when the document is added or deleted. The code is working nearly good. Now when the doc is added - toast appear. That works fine. But when i look at the read counter in my database - it increasing so quickly, like the function is 100% time reading all the data from database - not only for changes, like i want. I need to listen only for the changes in collection. Is it a way to do this in android?
I have a webapp and there my javascript code is working fine, read data only when the change appear.
Below my code:
public void listenToDocument() {
// [START listen_document]
myDatabase.collection("markery").addSnapshotListener(new EventListener<QuerySnapshot>()
{
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listen:error", e);
return;
}
for (DocumentChange documentChange : snapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:
String popup_data = documentChange.getDocument().getData().get("popup_data").toString();
GeoPoint geop = (GeoPoint) documentChange.getDocument().getData().get("geop");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, popup_data, Toast.LENGTH_LONG);
toast.show();
double lng = geop.getLongitude();
double lat = geop.getLatitude();
symbolLayerIconFeatureList.add(Feature.fromGeometry(
Point.fromLngLat(lng, lat)));
break;
case MODIFIED:
break;
case REMOVED:
break;
}
}
}
});
// [END listen_document]
}
When you add a listener to a query (or a collection reference, which is just a query for all documents in the collection), it will read all of the documents and deliver them all to your listener for the first invocation. There is no way to add a listener for only new and changed documents after some point in time.
If you want only new changes, you should add some sort of timestamp field that gets updates with each change, and filter your query using that timestamp, so that only newly modified documents will be delivered to the listener. For example:
myDatabase
.collection("markery")
.whereGreaterThan("timestamp", new Date())
.addSnapshotListener(...)
It will be up to you to make sure that timestamp is updated to the current time along with every update to every document in that collection.

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

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");

Giving the UID for the document's name

I would like to know what is the best practice to save users preferences in my firestore database.
I would try to explain with an example...
Case 1
I have this kind of Document in my "users" Collection (the name is random generated by Firebase) with 3 fields :
user_uid : String
nickname : String
android_lover : boolean
In my Android project, when I want to search the Document of the user "DFDDE45554SDC", I search where user_uid = "DFDDE45554SDC".
Case 2
I have this kind of Document in my "users" Collection (the name is created with the UID of the user) with 2 fields :
nickname : String
android_lover : boolean
In my Android project, when I want to search the Document of the user "DFDDE45554SDC", I just search the Document "DFDDE45554SDC".
I specify : I don't want duplicate users.
So, what is the best practice (security, optimisation,...) ? Why ?
I would suggest that Case 2 is more effective, for a few reasons:
We already know the user's ID, so don't need to use a different ID here.
Using usersCollection.document(userId) is simple to construct and is a direct DocumentReference, rather than a Query, therefore:
A DocumentReference can be stored in the Firestore database, whereas a Query cannot.
A DocumentReference would likely scale better than instructing the Firestore database to perform a filter query using whereEqualTo("user_uid", userId) (although with indexing, the performance difference is likely negligible at this point).
A Query will always return a collection of results (even if there is only 1), rather than the exact document.
There isn't currently a need for a different randomly-generated ID for each document within the users collection because the user ID is already unique.
You only need 1 document for each user, so this is a sure-fire way to ensure there won't be any duplicates.
The only real incentive I can think of to use Case 1 would be to standardise your document naming scheme with other collections in your database, but this doesn't really matter so much with Firestore.
For a quick example of the two in Android:
Case 1
db.collection("users")
.whereEqualTo("user_uid", "DFDDE45554SDC")
.limit(1)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
// Even with limit(1), we still receive a collection
// so iterate this to obtain the desired document
}
}
}
});
Case 2
db.collection("users")
.document("DFDDE45554SDC")
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
// We have access to the single desired document directly
DocumentSnapshot document = task.getResult();
}
}
});

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