Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search by place. String provider. Detekt. #42

Merged
merged 4 commits into from
Jun 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# Checklist
- [ ] I ran `./gradlew test connectedAndroidTest detekt`
- [ ] I rebased off of `upstream/master`
- [ ] At least 1 approving review - **@dellisd**, **@GustavoSanMartin**

# Issues
[issueName](issueURL)
Closed #

# Summary
Brief summary of what you committed

# Screenshots
Column1 | Column2
--- | ---
1 change: 0 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ apply plugin: 'kotlin-kapt'
apply plugin: 'kotlinx-serialization'
apply plugin: 'com.squareup.sqldelight'
apply plugin: "androidx.navigation.safeargs.kotlin"
apply plugin: "org.jlleitschuh.gradle.ktlint"

apply from: '../core_dependencies.gradle'
apply from: '../test_dependencies.gradle'
Expand Down
69 changes: 58 additions & 11 deletions app/src/main/java/ca/llamabagel/transpo/data/SearchRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,76 @@

package ca.llamabagel.transpo.data

import ca.llamabagel.transpo.BuildConfig.MAPBOX_KEY
import ca.llamabagel.transpo.R
import ca.llamabagel.transpo.data.OttawaBoundaries.MAX_LAT
import ca.llamabagel.transpo.data.OttawaBoundaries.MAX_LNG
import ca.llamabagel.transpo.data.OttawaBoundaries.MIN_LAT
import ca.llamabagel.transpo.data.OttawaBoundaries.MIN_LNG
import ca.llamabagel.transpo.data.db.TransitDatabase
import ca.llamabagel.transpo.di.StringsGen
import ca.llamabagel.transpo.ui.search.viewholders.SearchResult
import com.mapbox.api.geocoding.v5.MapboxGeocoding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

class SearchRepository @Inject constructor(private val database: TransitDatabase) {
suspend fun getStops(query: String): List<SearchResult> = withContext(Dispatchers.IO) {
val stops = database.stopQueries.getStopsByName("$query*").executeAsList()
val routes = database.routeQueries.getRoutes("$query%").executeAsList()
object OttawaBoundaries {
const val MIN_LAT = 45.203039
const val MIN_LNG = -76.227729
const val MAX_LAT = 45.513359
const val MAX_LNG = -75.351405
}

class SearchRepository @Inject constructor(private val database: TransitDatabase, private val strings: StringsGen) {

suspend fun getSearchResults(query: String): List<SearchResult> = withContext(Dispatchers.IO) {
if (query.isEmpty()) return@withContext emptyList<SearchResult>()

val searchResults = mutableListOf<SearchResult>()

if (routes.isNotEmpty()) {
searchResults.add(SearchResult.CategoryHeader("Routes"))
searchResults.addAll(routes.map { SearchResult.RouteItem("Name", it.short_name, it.type.toString()) })
getStops(query).takeIf { it.isNotEmpty() }?.let { stops ->
searchResults.add(SearchResult.CategoryHeader(strings.get(R.string.search_category_routes)))
searchResults.addAll(stops)
}

if (stops.isNotEmpty()) {
searchResults.add(SearchResult.CategoryHeader("Stops"))
searchResults.addAll(stops.map { SearchResult.StopItem(it.name, "• ${it.code}", "No upcoming trips") })
getRoutes(query).takeIf { it.isNotEmpty() }?.let { routes ->
searchResults.add(SearchResult.CategoryHeader(strings.get(R.string.search_category_routes)))
searchResults.addAll(routes)
}

searchResults
getPlaces(query).takeIf { it.isNotEmpty() }?.let { places ->
searchResults.add(SearchResult.CategoryHeader(strings.get(R.string.search_category_places)))
searchResults.addAll(places)
}

return@withContext searchResults
}

private suspend fun getStops(query: String): List<SearchResult.StopItem> = withContext(Dispatchers.IO) {
database.stopQueries
.getStopsByName("$query*")
.executeAsList()
.map { SearchResult.StopItem(it.name, "• ${it.code}", strings.get(R.string.search_stop_no_trips)) }
}

private suspend fun getRoutes(query: String): List<SearchResult.RouteItem> = withContext(Dispatchers.IO) {
database.routeQueries
.getRoutes("$query%")
.executeAsList()
.map { SearchResult.RouteItem("Name", it.short_name, it.type.toString()) } // TODO: update name parameter
}

private suspend fun getPlaces(query: String): List<SearchResult.PlaceItem> = withContext(Dispatchers.IO) {
MapboxGeocoding.builder()
.accessToken(MAPBOX_KEY)
.query(query)
.bbox(MIN_LNG, MIN_LAT, MAX_LNG, MAX_LAT)
.build()
.executeCall()
.body()
?.features()
?.map { feature -> SearchResult.PlaceItem(feature.placeName().orEmpty(), feature.text().orEmpty()) }
.orEmpty()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import ca.llamabagel.transpo.data.db.TransitDatabase
import ca.llamabagel.transpo.models.trips.ApiResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import javax.inject.Inject

class TripsRepository @Inject constructor(
Expand All @@ -24,7 +25,7 @@ class TripsRepository @Inject constructor(
suspend fun getTrips(stopCode: String): Result<ApiResponse> = withContext(Dispatchers.IO) {
try {
Result.Success(apiService.getTrips(stopCode).await())
} catch (e: Exception) {
} catch (e: IOException) {
Result.Error(e)
}
}
Expand Down
10 changes: 9 additions & 1 deletion app/src/main/java/ca/llamabagel/transpo/di/CoreModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

package ca.llamabagel.transpo.di

import android.content.Context
import androidx.annotation.StringRes
import ca.llamabagel.transpo.BuildConfig
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
Expand Down Expand Up @@ -39,5 +41,11 @@ class CoreModule {

@Provides
fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder().addInterceptor(interceptor).build()
OkHttpClient.Builder().addInterceptor(interceptor).build()

@Provides
@Singleton
fun provideStringsProvider(context: Context): StringsGen = object : StringsGen {
override fun get(@StringRes strResId: Int) = context.getString(strResId)
}
}
11 changes: 11 additions & 0 deletions app/src/main/java/ca/llamabagel/transpo/di/StringsGen.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* Copyright (c) 2019 Derek Ellis. Subject to the MIT license.
*/

package ca.llamabagel.transpo.di

import androidx.annotation.StringRes

interface StringsGen {
fun get(@StringRes strResId: Int): String
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ class TransitDatabaseModule {

@Provides
@Singleton
fun provideSqlDriver(context: Context): SqlDriver = AndroidSqliteDriver(TransitDatabase.Schema, context, "transit.db")
fun provideSqlDriver(context: Context): SqlDriver =
AndroidSqliteDriver(TransitDatabase.Schema, context, "transit.db")
}
6 changes: 5 additions & 1 deletion app/src/main/java/ca/llamabagel/transpo/di/TripsModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ abstract class TripsModule {
companion object {
@Provides
@JvmStatic
fun provideTripsService(adapter: CoroutineCallAdapterFactory, converter: Converter.Factory, okHttpClient: OkHttpClient): TripsService = Retrofit.Builder()
fun provideTripsService(
adapter: CoroutineCallAdapterFactory,
converter: Converter.Factory,
okHttpClient: OkHttpClient
): TripsService = Retrofit.Builder()
.baseUrl(BuildConfig.API_ENDPOINT)
.client(okHttpClient)
.addCallAdapterFactory(adapter)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ class HomeFragment : Fragment() {
val info = it[0]

val finished = info.state.isFinished
requireView().findViewById<ProgressBar>(R.id.progress_bar).visibility = if (finished) View.INVISIBLE else View.VISIBLE
requireView().findViewById<ProgressBar>(R.id.progress_bar).visibility =
if (finished) View.INVISIBLE else View.VISIBLE
})

requireView().findViewById<Button>(R.id.open_button).setOnClickListener {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ class MapFragment : Fragment() {
view?.findViewById<MapView>(R.id.map_view)?.onLowMemory()
}

@Suppress("MagicNumber")
private fun prepareMap(map: MapboxMap) {
viewModel.getStops()
viewModel.stops.observe(this, Observer { stops ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,4 @@ package ca.llamabagel.transpo.ui.planner

import androidx.lifecycle.ViewModel

class PlannerViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
class PlannerViewModel : ViewModel() // TODO: Implement the ViewModel
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,4 @@ package ca.llamabagel.transpo.ui.saved

import androidx.lifecycle.ViewModel

class SavedViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
class SavedViewModel : ViewModel() // TODO: Implement the ViewModel
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import androidx.recyclerview.widget.RecyclerView
import ca.llamabagel.transpo.R
import ca.llamabagel.transpo.di.injector

private const val KEYBOARD_DELAY_TIME = 200L

class SearchActivity : AppCompatActivity() {

private val viewModel: SearchViewModel by viewModels { injector.searchViewModelFactory() }
Expand All @@ -34,7 +36,7 @@ class SearchActivity : AppCompatActivity() {
searchBar.postDelayed({
val keyboard = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
keyboard.showSoftInput(searchBar.findFocus(), 0)
}, 200)
}, KEYBOARD_DELAY_TIME)
}
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ class SearchAdapter(private val list: List<SearchResult>) : RecyclerView.Adapter

val layoutInflater = LayoutInflater.from(parent.context)
return when (viewType) {
SearchResultType.CATEGORY.id -> SearchCategoryViewHolder(
SEARCH_CATEGORY_HEADER_LAYOUT -> SearchCategoryViewHolder(
DataBindingUtil.inflate(layoutInflater, SEARCH_CATEGORY_HEADER_LAYOUT, parent, false)
)
SearchResultType.ROUTE.id -> SearchRouteViewHolder(
SEARCH_RESULT_ROUTE_LAYOUT -> SearchRouteViewHolder(
DataBindingUtil.inflate(layoutInflater, SEARCH_RESULT_ROUTE_LAYOUT, parent, false)
)
SearchResultType.STOP.id -> SearchStopViewHolder(
SEARCH_RESULT_STOP_LAYOUT -> SearchStopViewHolder(
DataBindingUtil.inflate(layoutInflater, SEARCH_RESULT_STOP_LAYOUT, parent, false)
)
SEARCH_RESULT_PLACE_LAYOUT -> SearchPlaceViewHolder(
DataBindingUtil.inflate(layoutInflater, SEARCH_RESULT_PLACE_LAYOUT, parent, false)
)
else -> throw IllegalArgumentException("Unknown search result type")
}
}
Expand All @@ -36,8 +39,14 @@ class SearchAdapter(private val list: List<SearchResult>) : RecyclerView.Adapter
is SearchResult.CategoryHeader -> (holder as SearchCategoryViewHolder).bind(item)
is SearchResult.RouteItem -> (holder as SearchRouteViewHolder).bind(item)
is SearchResult.StopItem -> (holder as SearchStopViewHolder).bind(item)
is SearchResult.PlaceItem -> (holder as SearchPlaceViewHolder).bind(item)
}
}

override fun getItemViewType(position: Int) = list[position].id
override fun getItemViewType(position: Int) = when (list[position]) {
is SearchResult.CategoryHeader -> SEARCH_CATEGORY_HEADER_LAYOUT
is SearchResult.RouteItem -> SEARCH_RESULT_ROUTE_LAYOUT
is SearchResult.StopItem -> SEARCH_RESULT_STOP_LAYOUT
is SearchResult.PlaceItem -> SEARCH_RESULT_PLACE_LAYOUT
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ class SearchViewModel @Inject constructor(private val searchRepository: SearchRe
}

fun fetchSearchResults(query: String) = viewModelScope.launch {
_searchResults.value = searchRepository.getStops(query)
_searchResults.value = searchRepository.getSearchResults(query)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright (c) 2019 Derek Ellis. Subject to the MIT license.
*/

package ca.llamabagel.transpo.ui.search.viewholders

import androidx.recyclerview.widget.RecyclerView
import ca.llamabagel.transpo.R
import ca.llamabagel.transpo.databinding.SearchPlaceBinding

const val SEARCH_RESULT_PLACE_LAYOUT = R.layout.search_place

class SearchPlaceViewHolder(private val binding: SearchPlaceBinding) : RecyclerView.ViewHolder(binding.root) {

fun bind(place: SearchResult.PlaceItem) {
binding.place = place
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,13 @@

package ca.llamabagel.transpo.ui.search.viewholders

enum class SearchResultType(val id: Int) {
CATEGORY(0), ROUTE(1), STOP(2)
}

sealed class SearchResult {

abstract val id: Int
data class CategoryHeader(val header: String) : SearchResult()

data class CategoryHeader(
val header: String,
override val id: Int = SearchResultType.CATEGORY.id
) : SearchResult()
data class RouteItem(val name: String, val number: String, val type: String) : SearchResult()

data class RouteItem(
val name: String,
val number: String,
val type: String,
override val id: Int = SearchResultType.ROUTE.id
) : SearchResult()
data class StopItem(val name: String, val code: String, val routes: String) : SearchResult()

data class StopItem(
val name: String,
val code: String,
val routes: String,
override val id: Int = SearchResultType.STOP.id
) : SearchResult()
data class PlaceItem(val primary: String, val secondary: String) : SearchResult()
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class TripsFragment : Fragment() {
view?.findViewById<MapView>(R.id.map_view)?.onLowMemory()
}

@Suppress("MagicNumber")
private fun prepareMap(map: MapboxMap) {
// TODO: Move this into a domain layer or something like damn
viewModel.viewerData.observe(this, Observer { items ->
Expand Down
43 changes: 43 additions & 0 deletions app/src/main/res/layout/search_place.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2019 Derek Ellis. Subject to the MIT license.
-->

<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

<variable
name="place"
type="ca.llamabagel.transpo.ui.search.viewholders.SearchResult.PlaceItem"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/xlarge"
android:layout_marginTop="@dimen/small">

<TextView
android:id="@+id/stop_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="@{place.primary}"
android:textSize="18sp"/>
dellisd marked this conversation as resolved.
Show resolved Hide resolved

<TextView
android:id="@+id/stop_routes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/stop_name"
android:text="@{place.secondary}"
android:layout_marginTop="@dimen/xxxsmall"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Loading