Im getting an object from firebase, and there are two ways how i can get object
this one
text1
15.10.2021
text3
12.10.2021
text2
29.11.2021
text4
1.1.2022
or this one
{text = text1 , date = 15.10.2021}
{text = text3 , date = 12.10.2021}
{text = text2 , date = 29.11.2021}
{text = text4 , date = 1.1.2022}
I am need to sort this object by dates like that
text3 12.10.2021
text1 15.10.2021
text2 29.11.2021
text4 1.1.2022
I'm trying to add all into list but I don't know how to sort them. in list it looks like this
[text1, 15.10.2021, text3, 12.10.2021, text2, 29.11.2021, text4, 1.1.2022]
Im doing that for RecyclerView, and initially im getting dates and strings from Firebase like that
List<String> reminder = new ArrayList<>();
List<String> date = new ArrayList<>();
dbf.child("Reminders").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
reminder.clear();
date.clear();
for(DataSnapshot child2 : snapshot.getChildren()) { // getting a data from DB to ArrayList for dropping into Adapter
for(DataSnapshot tChild : child2.getChildren()) {
if (tChild.getKey().equals("text")) {
reminder.add(tChild.getValue().toString());
rem = reminder.toArray(new String[reminder.size()]); // rem = String[]
}
if (tChild.getKey().equals("date")) {
date.add(tChild.getValue().toString());
dat = date.toArray(new String[date.size()]); // dat = String[]
}
}
mainRowAdapter rAdapter = new mainRowAdapter(MainActivity.this, rem,dat);
rv.setAdapter(rAdapter);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
and then in Adapter class im use method setText()
so, the question in the top
CodePudding user response:
Your dates are stored as strings in a format that is unfortunately not chronologically sortable. If you want to sort on dates, I recommend storing them in ISO-8601 format, such as "2021-10-15"
so that their lexicographical order matches their chronological order.
Once you have that format, you can retrieve the nodes from the database in the correct order with:
DatabaseReference reminders = dbf.child("Reminders");
Query remindersByDate = reminders.orderByChild("date");
remindersByDate.addValueEventListener(...
Also see: