You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

5. Connect your queries to your UI


In this chapter, you are going to display a list of Launch Sites in a RecyclerView.

Configure LaunchListAdapter

Open LaunchListAdapter and add a launches property:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListAdapter.kt
1class LaunchListAdapter(
2    private val launches: List<LaunchListQuery.Launch>
3) : RecyclerView.Adapter<LaunchListAdapter.ViewHolder>() {

LaunchListQuery.Launch is a typesafe generated model from your LaunchList.graphql query.

Bind the data to the UI

Use the launches property to bind items to your adapter:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListAdapter.kt
1    override fun getItemCount(): Int {
2        return launches.size
3    }
4
5    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
6        val launch = launches.get(position)
7        holder.binding.site.text = launch.site ?: ""
8    }

Pass the LaunchListAdapter to the RecyclerView

Create a new Adapter and pass it to your RecyclerView:

Kotlin
app/src/main/java/com/example/rocketreserver/LaunchListFragment.kt
1        lifecycleScope.launchWhenResumed {
2            val response = try {
3                apolloClient.query(LaunchListQuery()).await()
4            } catch (e: ApolloException) {
5                Log.d("LaunchList", "Failure", e)
6                null
7            }
8
9            val launches = response?.data?.launches?.launches?.filterNotNull()
10            if (launches != null && !response.hasErrors()) {
11                val adapter = LaunchListAdapter(launches)
12                binding.launches.layoutManager = LinearLayoutManager(requireContext())
13                binding.launches.adapter = adapter
14            }
15        }

Test your query

Hit the Run button. You now have a UI connected to your GraphQL queries 🚀

A basic list

It looks a bit plain, though. Next, you'll add more info to the list to make it look nicer!

Feedback

Edit on GitHub

Forums