I have a recyclerView full of CardViews that have 2 paramteres (Both of them are Strings), one of those is a title,I would like to have a button to sort them alphabetically based on the tittle.
since it doesn't have too many elements I decided to use the insertion sort which is o(n^2) and this is my implementation:
public void ISortDes(String[]strings){
int j;
String key;
int i;
for (j = 1; j < strings.length; j++)
{
key = strings[ j ];
for(i = j - 1; (i >= 0) ; i--)
{
if (key.compareTo(strings[i]) > 0){
break;
}
strings[ i+1 ] = strings[ i ];
}
strings[ i+1 ] = key;
}
for (int k = 0; k < strings.length; k++){
System.out.println(strings[k]);
}
}
It takes an array of Strings and orders them.
And this is the method of my RecyclerView that takes the parameters:
private void initializeData() {
categories = new ArrayList<>();
categories.add(new Categories("CARS", "CARS"));
categories.add(new Categories("SPORTS", "SPORTS"));
categories.add(new Categories("GAMING", "GAMING"));
categories.add(new Categories("GAMBLING", "GAMBLING"));
categories.add(new Categories("TECH", "TECH"));
categories.add(new Categories("NATURE", "NATURE"));
categories.add(new Categories("RANDOM", "RANDOM"));
categories.add(new Categories("COUSINE", "COUSINE"));
categories.add(new Categories("HISTORY", "HISTORY"));
categories.add(new Categories("MUSIC", "MUSIC"));
categories.add(new Categories("STUDIES", "STUDIES"));
}
I think that i need to pass somehow that first paramater to a String Array and then sort it.
The idea is to have the sorting method in a button in the same Activity where the RecyclerView is displayed and when pressed it would have to sort them without going to another Activity.
I'm kinda lost here.
In resume what i'm trying to do is to have a buttom that orders the elements (which in this case are CardViews) of a RecyclerView alphabetically based on the "title" paramater.
Is my idea right, do you have another way to do this, or what should i do in order to accomplish this?
Thanks a million.
The easiest way to sort a list is to use java.util.Collections
Collections.sort(categories, new Comparator<Categories>() {
@Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
This will compare the title character by character. and will sort your list from a to z.
Don't forget after the modification to notify the list that the data have changed with notifyDataSetChanged()
(from your RecyclerView.Adapter
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With