Skip to content

Instantly share code, notes, and snippets.

@chelseatroy

chelseatroy/LoginActivity

Last active May 31, 2020
Embed
What would you like to do?
Interact with API in Activity
class LoginActivity : AppCompatActivity() {
...
fun authenticate() {
val loginJob = Job()
val errorHandler = CoroutineExceptionHandler { _, exception ->
AlertDialog.Builder(this).setTitle("Error")
.setMessage(exception.message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setIcon(android.R.drawable.ic_dialog_alert).show()
}
val coroutineScope = CoroutineScope(loginJob + Dispatchers.Main)
var session: CanarySession? = null
coroutineScope.launch(errorHandler) {
session = MockyAPIImplementation().authenticate()
//DON'T ACTUALLY log people's authentication tokens in a production application
Log.i("Session Retrieved:", session.toString())
if (session?.token != null) {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
} else {
deliverAuthFailureMessage()
}
}
}
private fun deliverAuthFailureMessage() {
AlertDialog.Builder(this).setTitle("Whoops")
.setMessage("Wrong credentials. Try again?")
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setIcon(android.R.drawable.ic_dialog_alert).show()
}
}
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.