I am making a SearchView in the search bar to filter all processes that started or ended within a certain date.
I need to get a query of nodes inside processes and codes.
Here is my data structure and what I need to query:
I'm using this for the codes as an example:
//path of all posts
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("codes");
//get all data from this ref
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String hola = Objects.requireNonNull(ds.getValue()).toString();
if (ds.hasChild("process")) {
for (DataSnapshot dsa: ds.getChildren()) {
System.out.println("result" dsa);
/* if (!isEmpty(Objects.requireNonNull(dsa.child("ended").getValue()).toString())) {
System.out.println("result: " dsa.child("ended").getValue().toString());
}
*/
}
But I need to obtain the node of other children, preferably without changing the data structure:
I have a FirebaseRecyclerOption where everything is loaded, and I need to only show the holders filtered from the SearchView.
CodePudding user response:
Due to the formatting of the date in the string, it will not be possible to filter or sort the data on the server side. If it was formatted "yyyy.MM.dd a les HH:mm:ss" it would still be possible because they would be in order of magnitude, but arranged this way I can only imagine you reading all the nodes and reordering in a local list ( I don't think it's a good idea).
My suggestion is that you replace the format of this time field to something like a TIMESTAMP from the firebase itself with the server time or if they are custom times, convert them and re-store them.
If you do, you can create custom filters and order them on the server itself, as needed, using orderByChild(), orderByKey(), orderByValue(), limitToFirst(), limitToLast(), startAt(), startAfter(), endAt (), endBefore() and equalTo().
CodePudding user response:
If you're allowed to change the database schema, a more convenient way of storing the data would be to have a flattened structure like this:
Firebase-root
|
--- codes
|
--- $pushedId
|
--- code: 17240
|
--- proces: "Cajones"
|
--- user: "Jose Anton"
|
--- started: longNumberForStarted
|
--- ended: longNumberForEnded
Things I recommend:
- Don't use sequential numbers as keys in the database. Use the unique random IDs that are generated by the push() method.
- Don't store dates as strings, rather store them as timestamps.
In this way, you'll be able to filter the results as needed. And since you're using timestamps you'll be able to use startAt() or endAt() if you need.