I have fragment with ListView connected to custom ArrayAdapter. Also on this fragment I have TextView for to sort items by name. Currently it works in next style, when I input any text in this TextView I'm changing sorting order for SQL request, like so: On first positions I'm showing items which contain "entered text" and after that all other items.
Now I'm doing it from my view, by stupid way, I'm every time reselect data from database, with ordering by some specific order field, which = 1 if Name field contain "entered text" and = 0 if not contain.
Can somebody tell me if it's possible to sort ArrayList in this style without reselect data from database?
Here is my solution:
if (mActualFilter.equals("")) {
Collections.sort(mProductItems, new Comparator<ProductItem>() {
@Override
public int compare(ProductItem o1, ProductItem o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
} else {
Collections.sort(mProductItems, new Comparator<ProductItem>() {
@Override
public int compare(ProductItem o1, ProductItem o2) {
String mName1 = o1.getName();
String mName2 = o2.getName();
if ((mName1.toLowerCase().contains(mActualFilter.toLowerCase())) && (!mName2.toLowerCase().contains(mActualFilter.toLowerCase()))) {
return -1;
} else if ((!mName1.toLowerCase().contains(mActualFilter.toLowerCase())) && (mName2.toLowerCase().contains(mActualFilter.toLowerCase()))) {
return 1;
} else {
return 0;
}
}
});
}