I have received several requests to adjust the way list items are displayed on my media player application.
Currently any entry beginning with "The" is sorted with the T's as you would expect. Many users would like to sort the item using the second word in the title.
Can someone shed some light on where this would be done? Would it be adjusted while getting the cursor or when applying to listview?
Any help would be greatly appreciated.
Thank You,
Josh
UPDATE:
Thank you all for the answers, but I am still struggling to find apply the solutions suggested in my instance.
I am using a simple cursor to acquire the dataset. Snippet of the code it below:
audioCursor = getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, cols,
null, null,AudioColumns.ARTIST + " COLLATE LOCALIZED ASC");
startManagingCursor(audioCursor);
setListAdapter(new MyABCAdapter(this, R.layout.list_item,
audioCursor, new String[]{AudioColumns.ARTIST,MediaStore.Audio.Artists.NUMBER_OF_TRACKS},
new int[]{android.R.id.text1, android.R.id.text2}));
I also have a utility that successfully adjusts the entry text, changing "The Artist" to "Artist, The", but it is not applied until bindView and the list has already been sorted:
private String fixFileName(String fileName) {
...
if (fileName.startsWith("The")){
fileName = fileName.replace("The ", "");
fileName = fileName.concat(",The");
}
return fileName;
}
My questions are:
1) Is there any way to apply fixFileName to the Cursor before the list is created?
2) If that is not possible, is there a way to resort the listview after bindview?
Thanks!
Have your list items extend Comparable. In the compareTo(..) method, write the custom compare code, likely using a "the".equalsIgnoreCase(fileName.subString(0, 3)), to make "The..." a special case.
Are you using an ArrayList<String> for the titles? One way I can think of is to implement your own Comparable interface. That would include, inside the method compareTo(...), remove any word like "The, "A", etc. and return the comparison of the rest of the String.
When you add items into the list do a Collections.sort() with a custom Comparator.
class CustomComp implements Comparator
{
public int compare(Object obj1, Object obj2)
{
...
if(obj1.toString().toLowerCase().startsWith("the"))
sort by second word instead
...
}
}
Related
On the material page I found the following example for AutoCompleteTextView:
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
String[] dogArr = getResources().getStringArray(R.array.dogs_list);
List<String> dogList = Arrays.asList(dogsArr);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, layoutItemId, dogList);
AutoCompleteTextView autocompleteView =
(AutoCompleteTextView) findViewById(R.id.autocompleteView);
autocompleteView.setAdapter(adapter);
Source: https://materialdoc.com/components/autocomplete/
What is the point of this part:
List<String> dogList = Arrays.asList(dogsArr);
Why turning it into an ArrayList when the AutoCompleteTextView also takes a String array?
When you know only going to work with a fixed number of elements, you should Array. If not, use Lists.
My personal opinion is use list. Lists makes code very inflexible and easy to use.
You can initialize Java arrays at compile time, like:
String data[] = { "a", "b", "c" };
In old versions of Java there was also the case for type safety. ArrayList elements had to be casted to the original type whereas Java arrays where type safe.
Java arrays are part of the language and you will not be able to change them. ArrayList is part of the Java API. If you need (I do not recommend it though) you could substitute your own library to implement the ArrayList job
Check This Question For More Information
See This question
If you have an array, it has to have a fixed size. Dynamically adding and removing the elements are difficult to manage and you have to have new array created every time you add a new item. Similarly for removing item.
With ArrayList it is easy to manage as it doesn't get created with a static size. Thus at runtime you can easily add and remove elements.
ArrayList is the ideal datastructure to use here.
I have one realm list and i want to sort the list alphabetically.
Collections.sort(contacts, new java.util.Comparator<Contacts>() {
#Override
public int compare(Contacts l1, Contacts l2) {
String s1 = l1.getName();
String s2 = l2.getName();
return s1.compareToIgnoreCase(s2);
}
});
But this logic not woking i am posting crash report below, please kindly go through it.
java.lang.UnsupportedOperationException: Replacing and element is not supported.
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:826
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:757)at java.util.Collections.sort(Collections.java:1909)
Please kindly go through my post and suggest me some solution.
Sorting in Realm is pretty straight forward.
Here is an example:
Let's assume you want to sort the contact list by name, you should sort it when your querying the results, you will get the results already sorted for you.
There are multiple ways to achieve this
Example:
1) Simple and Recommended way:
// for sorting ascending
RealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name");
// sort in descending order
RealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name", Sort.DESCENDING);
Updated since realm 5.0.0
1) Simple and Recommended way:
// for sorting ascending, Note that the Sort.ASCENDING value is the default if you don't specify the order
RealmResults<Contacts> result = realm.where(Contacts.class).sort("name").findAll();
// sort in descending order
RealmResults<Contacts> result = realm.where(Contacts.class).sort("name", Sort. DESCENDING).findAll();
2) for unsorted results
If you are getting unsorted results you can sort them anywhere this way.
RealmResults<Contacts> result = realm.where(Contacts.class).findAll();
result = result.sort("name"); // for sorting ascending
// and if you want to sort in descending order
result = result.sort("name", Sort.DESCENDING);
Have a look here you will find very detailed examples about Realm querying, sorting and other useful usage.
Technically you should use the following:
RealmResults<Contacts> result = realm.where(Contacts.class)
.findAllSorted("name", Sort.DESCENDING);
It is recommended over findAll().sort().
Use this to get the sorting in SORT_ORDER_ASCENDING or SORT_ORDER_DESCENDING
public void sort(java.lang.String[] fieldNames, boolean[] sortAscending)
Check the API reference Reference 1 or Reference 2
I have custom ListView in my android application. It consists images and title and content like subtitle and price. Here I want to sort my ListView in price basis. Any one can help me? How to sort the ListView. For example pls refer the following link if possible to sort the list in degree basis...
http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text
You need to sort the data structure before setting in the listview. it is only the possible way i think
First sort your data like this
Collections.sort(myList, new Comparator<WeatherData>() {
#Override
public int compare(WeatherData lhs, WeatherData rhs) {
return lhs.degree.compareTo(rhs.degree);
}
});
and then apply it to your adapter.
I want to convert my ArrayList containing elements with the toString method shadowed in "T":
public String toString(){
return name + " " + realname;
}
to a CharSequence array containing all the "T"s toString. Checked some stuff out but nothing works for me since CharSequence[] can't be concatenated (correct me if i'm wrong).
Saw a solution for the ArrayList at -> ArrayList<String> to CharSequence[] which didn't work out for me
I'm doing this because I've searched for devices ("T") and added them to a Arraylist, the user then has to make a choice which one to accept by clicking on a mutliple choice dialogwindow as shown under DIALOG_TEXT_ENTRY in this link
Please help me out cause it's driving me mad
So through the responses via the comments you guys suggested a solution with subsequence. However this is a similar solution I guess and it's semi-implemented in my code already so I'm gonna go with this one with a few modifications ofcourse.
Feel free to still give feedback if it's a bad way to implement or if there actually exists other ways of doing it!
::EDIT::
The solution was the following: I tried ot the code given by the link and take note that my ArrayList.toString() returns a String object with the following look for each element in the List
"[foo, bar, super, duper]"
Taken to account that the toString() is overriden in the my object class. The following is done
private String[] stringToArray(String str){
str = str.substring(1, str.length()-1);
String[] str2array = str.split(", ");
return str2array;
}
And voila I have the String[] array and can now represent them as choices in my single choice list.
I'm trying to modify an existing notepad example from the Android Developer site. I have a database with an existing column named CREATED_DATE(of the note) but the data for that column is presented as System.currentTimeMillis(). This is all good and probably in line with conventions since it's created by the developers.
But my problem is that I want to present the date in a ListView using the format "30 sep". My problem, how do I convert the data to that format before presenting it in the ListView? Right now I'm using this kind of adapter:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.noteslist_item, cursor,
new String[] { Notes.TITLE, Notes.CREATED_DATE }, new int[] { R.id.note_title, R.id.note_date });
setListAdapter(adapter);
Now, I've figured out how to convert currentTimeMillis() to today's date but how can I convert the data coming from the cursor before I toss it into the adapter?
If I understand your question correctly, take a look at the Date and SimpleDateFormat classes in order to convert your ms long into a String representation.
(There are lots of examples on stackoverflow on how to actually use those classes)
You have to change the ViewBinder. Have a look at this Changing values from Cursor using SimpleCursorAdapter
It helped me..