I am trying to make a search result to show a list of documents from firestore collection based on the keyword found in a field from the document.
I saw that the firestore how-to-guides show something like this:
citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco");
I tried but the result that came out isn't correct at all.
This is the class that show query results based on the keyword retrieved from the last activity using intentextra.
I am not sure how to fix it, if anyone who's familiar with firestore could help me, I would be really grateful. Thanks.
public class SearchActivity extends AppCompatActivity {
private TextView showKeyword;
private RecyclerView recyclerView;
private JournalAdapter adapter;
private List<Journal> journalList;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private String userId;
private CollectionReference userIdRef;
private String keywordString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
showKeyword = (TextView) findViewById(R.id.keywordTextView);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewSearch);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
journalList = new ArrayList<>();
adapter = new JournalAdapter(this, journalList);
recyclerView.setAdapter(adapter);
//firestore
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
userIdRef = db.collection("main").document(userId).collection("journal");
showData();
}
private void showData() {
Intent intent = getIntent();
keywordString = intent.getStringExtra("keyword");
showKeyword.setText(keywordString);
//problem, funny result
userIdRef.whereGreaterThanOrEqualTo("description", keywordString)
.orderBy("description")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
assert queryDocumentSnapshots != null;
if (!queryDocumentSnapshots.isEmpty()){
//if not empty
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot documentSnapshot : list) {
Journal journal = documentSnapshot.toObject(Journal.class);
assert journal != null;
journal.setId(documentSnapshot.getId());
journalList.add(journal);
}
adapter.notifyDataSetChanged();
} else {
//if empty
Toast.makeText(SearchActivity.this, "No result with the word " + keywordString + " is found", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SearchActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}