How to query an array list in a Firebase document? - java

I'm trying to query my database for an android application, if a username is in the 'fave' array field of my database and if so then change the background of an image. My database is set up like this...
I don't know if i'm doing it right but currently i think i may be checking the whole collection rather than a specific document and it's not even returning anything. Any suggestions would be appreciated!

You wanted this?
FirebaseFirestore.getInstance().collection("Trainers").document("Air Force 1 Low").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
List<String> list = (List<String>)documentSnapshot.get("fave");
for (String name : list){
if (name.equals("Admin")){
//do if user is admin
return;
}
}
//do if user is not admin
}
});

Related

How can I perform OR query while searching in firebase?

Here are the various attributes of a person.
I want to implement a search where the results come if any of the fields: specializationField, hospitalName or fullName have the same letters.
For example if I search 'sh', this person should appear in the field, because of the similar hospital name.
This is the code I am using to search only for fullName:
FirebaseRecyclerOptions<DoctorHelperClass> options =
new FirebaseRecyclerOptions.Builder<DoctorHelperClass>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Doctor").orderByChild("fullName").startAt(s.toUpperCase()).endAt(s.toLowerCase()+"\uf8ff"), DoctorHelperClass.class)
.build();
adapter = new DoctorsAdapters(options, FindDoctorActivity.this);
adapter.startListening();
binding.rvListDoctors.setAdapter(adapter);
Please help me out
As #Puf said, you can't achieve it at Firebase Realtime Database but you can do it at client side which mean at the Android part.
First, you cannot use FirebaseUI which is you are currently using, instead you need to use https://firebase.google.com/docs/database/android/read-and-write#read_data
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// You have to make for each loop
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
DoctorHelperClass doc = snapshot.getValue(DoctorHelperClass.class);
//List them in an array
docList.add(doc);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mPostReference.addValueEventListener(postListener);
Once you have added all the list of doctors. You can compare them using the arrayList.
You can do something like this.
private void searchDoc(final String inputDoc){
boolean isFound = false;
for (DoctorHelperClass doc in docList){
if (doc.getFullName() == inputDoc && doc.getHospitalName() == inputDoc){
isFound = true;
//Do something if found
}
}
}
I hope you get the concept of it.
There is no support for OR conditions in Firebase Realtime Database. You will either have to perform multiple queries and merge the results client-side, or create a specialized field for performing this search.
But given your question, you may be looking for text search capabilities that are well beyond what Firebase Realtime Database handles. Instead of trying to shoehorn those requirements onto Firebase, I recommend using an additional (or even other) database for meeting your text search requirements.
Also see:
Use firebase realtime database create search function
How to search anywhere in string in Firebase Database - Android
Searching in Firebase without server side code
Firebase and indexing/search

Is there any way to only proceed once I have obtained data from Firebase in Android?

I am working on an app for a hotel, which enables hotel management to report and view concerns and issues. I am using Android and Firebase for this app.
Here is the database structure of a reported concern:
To minimize data download and optimize speed, I am adding "Active" and "Resolved" nodes in the database, like below:
Now, the hotel wants me to add the function to create an Excel report of concerns closed/resolved within the past month. For this, I will be attaching a Single Value Event Listener on the "resolved" node, get keys of resolved concerns, then for each key, fetch data from "allConcerns" node, store each node's data into an ArrayList of String. After which I will use this JSON to Excel API for Android to create Excel file.
I am able to access keys of resolved concerns with this code:
DatabaseReference resolvedReference = FirebaseDatabase.getInstance().getReference()
.child(getApplicationContext().getResources().getString(R.string.concerns))
.child(getApplicationContext().getResources().getString(R.string.resolved));
final ArrayList<String> keys = new ArrayList<>();
resolvedReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//Getting keys of all resolved concerns in keys arraylist here
for (DataSnapshot ds : snapshot.getChildren()){
keys.add(ds.getValue(String.class));
}
//Storing JSON data in this arraylist
final ArrayList<String> data = new ArrayList<>();
for(int i = 0; i<keys.size() ; ++i){
String key = keys.get(i);
//Getting data of each concern here
FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.allConcerns))
.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String type = snapshot.child("type").getValue().toString();
Log.i("Type", type);
if(type.equals("0")) {
SafetyConcernClass s = snapshot.getValue(SafetyConcernClass.class);
Log.i("Snapshot of key", s.toString());
data.add(s.toString());
}
else{
GembaWalkClass g = snapshot.getValue(GembaWalkClass.class);
Log.i("Snapshot of key", g.toString());
data.add(g.toString());
}
Proof proof = snapshot.child("proof").getValue(Proof.class);
Log.i("Proof", proof.toString());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
//Issue I am facing is here
Log.i("Data size", String.valueOf(data.size()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
The real issue here is while logging data.size(). Since Firebase is asynchronous, FOR loop ends before data is fetched and entered into the data ArrayList, hence it gives me a size of 0. And since no data is fetched, I can't create an Excel file.
My question is, how can I make sure I am proceeding to log data.size() ONLY after data of respective resolved concerns is stored in the ArrayList?
The typical approach is to keep a counter or a countdown latch to track how many of the concern snapshots you've already downloaded. Once the counter reaches keys.size() you know that you're done.
Also see Setting Singleton property value in Firebase Listener
You should write your method
addListenerForSingleValueEvent
using AsyncTask or Kotlin coroutines
and in onPostExecute() of AsyncTask, you can proceed to further action.

How to query a document field inside of queryDocumentSnapshot Firestore

I am building a chatroom application and am trying to query all messages then separate them accordingly based on the message sender.
This is what my Firestore architecture looks like:
And my code so far:
CollectionReference chatRoomMsgs = db.collection("chatrooms").document(chatRoomID).collection("Messages");
chatRoomMsgs.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
if(documentSnapshot.get("sentby") == firebaseUser.getUid()){
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
What I am (currently) trying to do is pull ALL chatroom messages first, and then separate them out in onSuccess.
I am trying to say "ok if the message was sent by this user, grab the image field value of that same document and add it to an array so the image can be accessed later, and if the message was not sent by the same user, also grab the image url but add it to a different array"
How can I do this? Thanks!
Update
I tried adding the while loop below to get some sort of output, wasn't triggering
ArrayList<String> sentPics = new ArrayList<String>();
while(documentSnapshot.get("sentby") == firebaseUser.getUid()){
sentPics.add(documentSnapshot.get("image").toString());
Log.d("PICLIST", sentPics.toString());
}
If you want to get all the messages sent by a specific user, then you should use the following query:
CollectionReference chatRoomMsgs = db.collection("chatrooms").document(chatRoomID).collection("Messages");
Query sendByQuery = chatRoomMsgs.whereEqualTo("sentby", firebaseUser.getUid());
sendByQuery.addOnSuccessListener(/* ... */);
Using this solution you'll significantly reduce the number of read operations as you get as a result only the messages that correspond to the logged-in user.
Your solution is very expensive because you are getting all messages that exist in the Messages collection and you filter them on the client. If you have a total of 100 messages in the collection but only 10 correspond to the logged-in user, you'll be charged with 100 reads. In my solution, you'll only be charged with 10, as the query only 10 messages returns.
If want to see another approach, here you can find a tutorial on how to create a complete and functional Firestore Chat App.
What you need to do is make a POJO named Message that maps to your Messages collection with member variables image and sentby and convert the documentSnapshot to a Message object using:
Message message = documentSnapshot.toObject(Message.class)
From there on, you can just use the getters to achieve what you want.
Hope it helps!

Query Firestore data and add one field to all the documents that match the query

I am building an Android app to sell books. My users can post ads for their used books and sell them. I am planning to add a feature where my users can opt to go anonymous. There will be checkbox with name Make me anonymous. If users check that box, their phone number and name will not be visible to others. Only a generic name should be visible.
Now the problem is, I want to put an entry anonymous = true in every ad documents that the user uploaded.
I want to query the ads that the user put and add a field anonymous = true. I want to do something like below:
final CheckBox anonymousCB = findViewById(R.id.anonymousCB);
anonymousCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (anonymousCB.isChecked()){
WriteBatch batch = firestore.batch();
DocumentReference sfRef = firestore.collection("books").whereEqualTo(uid,uid);
batch.update(sfRef, "anonymous", "true");
}
}
});
But I cannot make a query and insert a field into all the documents that match the query. Is there any better way to do this?
Is there any better way to do this?
Yes, there is. To solve this, please use the following lines of code inside onCheckedChanged() method:
Query sfRef = firestore.collection("books").whereEqualTo(uid, uid);
sfRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
for (String id : list) {
firestore.collection("books").document(id).update("anonymous", true).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "anonymous field successfully updated!");
}
});
}
}
}
});
The result of this code would be to add the anonymous property to all your book objects and set it to true. Please note, I have used the boolean true and not the String true as you have used in your code. Is more convenient to be used in this way.
P.S. If you are using a model class for your books, please also see my answer from this post.

Parse powered by Bitnami for Android (friends list)

So I have written an on click method that takes in text from a user (a friend's name) then checks to see if that user exists on the database and if you are already friends with that user. If the user exists and isn't already your friend, I want it to add them to your friends list, which is an array on the Parse backend. The checks seem to be working, and "frank" is added to the list on the device however the list isn't being updated or saved on the server and I can't work out why, I've checked variable and database names for error and I cant find any. I'm testing logged in as "bill". Please find method and screenshot of database below. Any help would be greatly appreciated.
Parse bitnami database here
public void addFriend(View view){
final EditText mText = (EditText)findViewById(R.id.editText);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", mText.getText().toString());
query.countInBackground(new CountCallback() {
#Override
public void done(int count, ParseException e) {
if (e == null) {
if(count==0){
Toast.makeText(getApplicationContext(), "User Doesn't Exist", Toast.LENGTH_LONG).show();
}
else if (ParseUser.getCurrentUser().getList("friendsList").contains(mText.getText().toString()))
{Toast.makeText(getApplicationContext(), "User is already a friend", Toast.LENGTH_LONG).show();}
else
{
ParseUser.getCurrentUser().getList("friendsList").add(mText.getText().toString());
ParseUser.getCurrentUser().saveInBackground();
}
}
}
});
}
I haven't used Parse much myself, but from the API documents here: http://docs.parseplatform.org/android/guide/#arrays
It looks like what is happening is you are using the .add() method from List<>, but it seems you need to use the Parse's specific .add() method on the ParseObject.
Try changing this line:
ParseUser.getCurrentUser().getList("friendsList").add(mText.getText().toString());
to
ParseUser.getCurrentUser().add("friendsList", mText.getText().toString());

Categories