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
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:
Firebase sort by points depending on date
Firebase endAt() not working with date string?
Querying by range in firebase
Related
I have 5 elements in RecyclerView(elements taken from DB) with dates and texts. Two different lists. For dates and for strings. One fragment contains 1 date and 1 string text. So, im need to sort elements by date, like that
Result which i want
text1 10.09.2021
text2 13.09.2021
text3 30.09.2021
text4 1.12.2021
Result which i have
text3 30.09.2021
text4 1.12.2021
text1 10.09.2021
text2 13.09.2021
texts and dates is a two different Lists
The question is, how i can sort dates as strings(may be?) with no text loss, and where im supposed to do that (after getting from db and before retrieve data in adapter? or after loading elements in adapter and then getting them back for sort (looks bad)
thats how im get data from DB and retrieve in adapter
List<String> reminder = new ArrayList<>();
List<String> date = new ArrayList<>();
Calendar test = Calendar.getInstance();
long pars = test.getTimeInMillis();
System.out.println(pars);
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()]);
}
if (tChild.getKey().equals("date")) {
date.add(tChild.getValue().toString());
dat = date.toArray(new String[date.size()]);
}
}
mainRowAdapter rAdapter = new mainRowAdapter(MainActivity.this, rem,dat);
rv.setAdapter(rAdapter);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
setText in AdapterClass
holder.reminder.setText(reminder[position]);
holder.date.setText(date[position]);
in another topic i saw this one, but this cannot help me in my situation? may be some analogies exist?
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
the best place to sort your data is when you get your data from db by a query, but if you want to do it manually on your list the best format for saving your date is like this:
2021.09.10
2021.09.13
2021.09.30
2021.12.01
because string sort can apply to your date.
To sort the dates in descending order, you can simply use:
collections.reverseorder();
This is my firebase realtime database :
This is my code :
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
EditText t1 = (EditText) findViewById(R.id.editText10);
final String s1 = t1.getText().toString();
mDatabase.child("users").orderByChild("name")
.equalTo(s1)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
}
}
I am entering these values in EditText fields :
editText10 => Anupam Singh
dataSnapshot.getChildrenCount() should be 1 but it is coming to be 0.
What am I doing wrong?
In your database you have the following:
users
name_title_company_location
Therefore the attribute name_title_company_location is a direct child under nodeusers. When you are using orderByChild, you are not accessing that node.
What you need to do is add an id in the database:
users
id
name_title_company_location
Then your code will work.
Or you can change the code to the following, go one level up:
mDatabase.orderByChild("name_title_company_location").equalTo(...)
-the issue is in orderByChild.
-you have pass query and ask for single value event listener.
do as below :
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
Query query = mDatabase.("name_title_company_location")
.equalTo(s1 + "_" + s2 + "_" + s3 + "_" + s4);
query.addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
}
}
-it will return the data
I have a firebase database that has a name and number in it for each of my stores. I want a spinner to show the names of each store so we can select one. the store name example is "0023 franklin", and i want to order them by the number.
my code to make the spinner is
mydb.orderByValue().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Is better to use a List, because you don't know the size
// of the iterator returned by dataSnapshot.getChildren() to
// initialize the array
final List<String> areas = new ArrayList<String>();
for (DataSnapshot areaSnapshot: dataSnapshot.getChildren()) {
Store storeName = areaSnapshot.getValue(Store.class);
areas.add(storeName.getStoreName());
}
Spinner areaSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(checkout.this, android.R.layout.simple_spinner_item, areas);
areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaSpinner.setAdapter(areasAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
it shows all the stores but doesn't order them by the number. and the stores are not added in the database in order.
how to i make this happen?
adding JSON
storelist:
-KvIoZC0AbpD1-SJJrIS
faxNum: 987654321
storeName: 0024 Franklin
-KvIobgHLouocLpMkN6k
faxNum: 1234567890
storeName: 0003 Randle
You can use any of the following methods to sort the data:
orderByChild()
orderByValue()
orderByKey()
You can store that number with a key like 'storeNumber' and use the available method like:
orderByChild("storeNumber");
for more usage refer to :
https://firebase.google.com/docs/database/android/lists-of-data?authuser=0#sort_data
I'm using order by child to spisplay data into listView and the data is displayed by descending order, How can I set the order to ascending order in Android client Side?
ref.orderByChild("date_creation").limitToFirst(10).addValueEventListener(new ValueEventListener() {
//date_creation is the date when user add Book "dd-MM-yyyy_HH:mm:ss"
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
String prixLivreToDisplay = valueBook.getPrix_livre();
String timeToDisplay = valueBook.getDate_creation();
String filePathToDiplay = valueBook.getChemin_image();
String villeToDisplay = valueBook.getVille_livre();
String typeAnnToDisplat = valueBook.getType_annonce_selected();
item = new Book();
item.setNom_livre(titreLivreToDisplay);
item.setDesc_livre(descLivreToDisplay);
item.setPrix_livre(prixLivreToDisplay);
item.setDate_creation(timeToDisplay);
item.setChemin_image(filePathToDiplay);
item.setVille_livre(villeToDisplay);
item.setType_annonce_selected(typeAnnToDisplat);
feedItems.add(item);
}
listAdapter = new FeedListAdapter(AccueilActivity.this, feedItems);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
I want use Arraylist collections to sort data that I get From Database.
List<String> list = new ArrayList<String>();
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
String prixLivreToDisplay = valueBook.getPrix_livre();
String timeToDisplay = valueBook.getDate_creation();
String filePathToDiplay = valueBook.getChemin_image();
String villeToDisplay = valueBook.getVille_livre();
String typeAnnToDisplat = valueBook.getType_annonce_selected();
list.add(titreLivreToDisplay);
list.add( descLivreToDisplay);
list.add(prixLivreToDisplay);
list.add(timeToDisplay);
list.add(filePathToDiplay);
list.add( villeToDisplay);
list.add(typeAnnToDisplat);
Collections.sort(list);
I don't know how to implement that. How can I use this collections? How to use list to feed feedItems?
From what you explained, you only want to reverse the order of your list.
This can be easily done using a comparator.
// Defining the comparator
Comparator compare = Collections.reverseOrder();
// Sorting the list taking into account the comparator
Collections.sort(list, compare);
This code should reverse order your list.
Hope I have helped, otherwise, provide more information about the reverse order stage.
I want sorted data by ascending order , the solution was just use collections to reverse order that I had:
Collections.reverse(feedItems);
I have database structure like this in Firebase
I want to search a search on this structure based on key number and get the parent key in return. Meaning if i search for 8860124421 then i should get -KTEtSR7chN8te1WaW-W in return .
I am doing it like this in android -
final String number = "8860124421";
DatabaseReference global_user_entry_ref = ApplicationContext.getGlobalDataBaseReference()
.child("User-Entry-2").getRef(); //Reference to User-Entry-2
Query query = global_user_entry_ref.orderByChild("number").equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
for(DataSnapshot friend: dataSnapshot.getChildren()){
String firebase_id = (String) friend.getKey();
Log.d("ContactSync","handle number "+firebase_id+" "+number+" "+friend);
}
Log.d("ContactSync","handle number outer "+dataSnapshot);
//user exist
}
else {
//user_does_not_exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("ContactSync","handle number oncancel "+databaseError.getMessage());
}
});
But I am not getting proper result , dataSanpshot in onDataChange looks like this -
DataSnapshot { key = User-Entry-2, value = null }
but i want to get dataSnapShot with parent of number key.
Please help , Thanks in advance
As #Frank van Puffelen stated in comments , the problem was that i was comparing a number from code with a string in the database , which does not match , Therefore the solution is to change
final String number = "8860124421";
to
final long number = 8860124421;