diff --git a/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt b/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt --- a/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt +++ b/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt @@ -1,5 +1,6 @@ package it.reyboz.bustorino.util +import android.util.Log import it.reyboz.bustorino.backend.Stop class StopSorterSearch(val searchById: Boolean): Comparator { @@ -17,14 +18,38 @@ } else if(s1.location==null) return -1 if(searchById){ + val g1 = s0.gtfsID + val g2 = s1.gtfsID + if(g1!=null && g2!=null){ + try { + val c0 = g1.split(":").get(1).toInt() + val c1 = g2.split(":").get(1).toInt() + + return c0 - c1 + } catch (e: NumberFormatException) { + Log.w(DEBUG_TAG,"Tried comparing stop gtfs ID but it is not numeric: ${s0.gtfsID} <-> ${s1.gtfsID}") + } + } + val lenDiff = s0.ID.length - s1.ID.length - if(lenDiff!=0) return lenDiff + if (lenDiff != 0) return lenDiff //second criterion - val diff = s0.ID.toInt() - s1.ID.toInt() - //if(diff!=0) return diff - return diff + try { + val diff = s0.ID.toInt() - s1.ID.toInt() + return diff + } catch (e: NumberFormatException) { + Log.e(DEBUG_TAG, "Cannot convert stop ID to Int: ", e) + return -1 * (s0.numRoutesStopping - s1.numRoutesStopping) + } + + } else{ + //TODO: Improve probably the sorting with the name case return -1*(s0.numRoutesStopping - s1.numRoutesStopping) } } + + companion object{ + private const val DEBUG_TAG = "BusTO-StopSorterSearch" + } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt --- a/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt +++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt @@ -37,14 +37,18 @@ } else { delay(250.milliseconds) - //showQueryResult.postValue(true) + if(r.byId){ + try{ + val c = r.q.toInt() + } catch (e: NumberFormatException){ + Log.w(TAG, "Tried to search stop by Id but query is not numeric: ",e) + emit(emptyList()) + //do nothing else + return@liveData + } + } val list = nextGenDB.searchStopsByCodeOrName(r.q, r.byId) - /*if (r.byId) - emit(list.sortedBy { it.ID }) - else - emit(list.sortedBy { it.numRoutesStopping }.reversed()) - */ emit(list.sortedWith(StopSorterSearch(r.byId))) } }