Created
January 25, 2019 10:49
-
-
Save andijakl/56cd8c30666c50e434f8f94acac0fe8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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