I have two tables in mysql which bind \'Categories\' and \'products\' through ids \'id_catprods\' and \'ID_Cat\'. So far so good, I\'m working on Android with \"ExpandableListVi
Sort them when querying in MySql if possible. Otherwise, here is one suggestion. Store the categories in a ArrayList<String>
. You can easily sort them using one of Collection.sort()
. Then, store your products in a Hashtable<String, ArrayList<Product>>
where the key is the category name and the data is a Product class that stores your product details. You can sort your Product class using an Comparator<Product>
. You will need to modify the adapter accordingly.
Use
Collections.sort(arraylist);
or
list.sort(String::compareToIgnoreCase);
This will sort your arraylist and If you have Expandable list you have to use
Collections.sort(arraylist, new Comparator<Modelclass>(){
@Override
public int compare(Modelclass o1, Modelclass o2) {
Collections.sort(o1.getsubarraylist(), new Comparator<Modelclass>(){
@Override
public int compare(Modelclass o1, Modelclass o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
Collections.sort(o2.getsubarraylist(), new Comparator<Modelclass>(){
@Override
public int compare(Modelclass o1, Modelclass o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
return o1.getName().compareToIgnoreCase(o2.getName());
// *This Sorts The Group's if you don't wanna sort group simply return 0*;
}
});
NOTE:- o1.getsubarraylist() & o2.getsubarraylist() is Child list's of a expandable list, Just add inner Collections.sort() for sorting expandable list's
or if you have Simple String arraylist
Collections.sort(arraylist, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
I hope this helps someone in need....
Better and easy way to sort Categories with product is from mysql
query. You can use inner join
or any other which fits on your case to sort and make relation between products and categories.