Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MainActivity : AppCompatActivity() {
// Reference to the RecyclerView adapter
private lateinit var adapter: PartAdapter
private fun loadPartsAndUpdateList() {
// Launch Kotlin Coroutine on Android's main thread
GlobalScope.launch(Dispatchers.Main) {
// Execute web request through coroutine call adapter & retrofit
val webResponse = WebAccess.partsApi.getPartsAsync().await()
if (webResponse.isSuccessful) {
// Get the returned & parsed JSON from the web response.
// Type specified explicitly here to make it clear that we already
// get parsed contents.
val partList : List<PartData>? = webResponse.body()
Log.d(tag, partList?.toString())
// Assign the list to the recycler view. If partsList is null,
// assign an empty list to the adapter.
adapter.partItemList = partList ?: listOf()
// Inform recycler view that data has changed.
// Makes sure the view re-renders itself
adapter.notifyDataSetChanged()
} else {
// Print error information to the console
Log.d(tag, "Error ${webResponse.code()}")
Toast.makeText(this@MainActivity, "Error ${webResponse.code()}", Toast.LENGTH_SHORT).show()
}
}
}
// For reference: shortened code of onCreate. See the full example on Github for
// commented code.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// rv_parts is the recyclerview UI element in the XML file
rv_parts.layoutManager = LinearLayoutManager(this)
// Create the adapter for the recycler view, which manages the contained items
adapter = PartAdapter(listOf(), { partItem : PartData -> partItemClicked(partItem) })
rv_parts.adapter = adapter
// Start loading recycler view items from the web
loadPartsAndUpdateList()
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.