Anthony Taylor Anthony Taylor - 1 year ago 70
Android Question

Sorting Objects Alphanumerically

I am running into an issue when trying to sort a List of "Routes" for my app, no matter what I try, I cannot obtain the sorting that I am looking for.

I want it sorted 1,2,3,4,5, etc but when I sort, I get 1,11,12,2,20 and so on.

My Route model is

public open class Route(docValue:Map<String,Any>) {
val route_id = (docValue["route_id"] as Number).toInt()
val short_name = docValue["route_short_name"] as String
val color = readColorMoreSafely(docValue, "route_color", Color.BLUE)
val long_name = docValue["route_long_name"] as String

The code used to sort is

if(cityId != null && view != null) {
val routesList = view.findViewById( as ListView
val cache = TransitCache.getInstance(applicationContext, cityId, true)
val routes = cache.getRoutes()
.doOnNext {
val noRoutesMessage = view.findViewById( as TextView
noRoutesMessage.visibility = if(it.size == 0) View.VISIBLE else View.GONE
listAdapter = RxListAdapter(applicationContext, R.layout.activity_list_routes_row, routes)
routesList.adapter = listAdapter

But still nothing, I just want to sort the routes by "route_id", i've tried a few different things, the last one of which was


which still ended up not doing what I wanted, at this point I'm stuck.

Answer Source
val routes = cache.getRoutes()

This code tells me you're dealing with RxJava, which requires an entirely different solution so in the future it is important to include that type of information.

If cache.getRoutes() returns an Observable<List<Route>> then that route can be sorted with the code

.map { 

This will produce a new inner list sorted by the numerical value of route_id.

If cache.getRoutes() returns Observable<Route> then you need to include the additional call to .toList() to turn it into an Observable<List<Route>>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download