Hi All,
I’m new to Kotlin, and android dev in general. I have developed a web app that has a local DB and login credentials. My app can successfully post to that web app to verify login, but when I try to switch fragments after that, I get an error “Method setCurrentState must be called on the main thread”
See my onViewCreated of my FirstFragment below. Note that if I put the findNavController() line directly into the button listener, it works. It just fails within the callback.
Thank you!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//urlButton listener
binding.loginButton.setOnClickListener() {
//on button click
val url = "https://redacted/mobile/login"
Log.i("Testing", "Attempting Client Connection")
val formBody: RequestBody = FormBody.Builder()
.add("username", binding.usernameInput.text.toString())
.add("password", binding.passwordInput.text.toString())
.build()
val okHttpClient = OkHttpClient()
val request = Request.Builder()
.post(formBody)
.url(url)
.build()
Log.i("Testing", url.toString())
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle this
Log.i("Failed", e.toString())
}
override fun onResponse(call: Call, response: Response) {
// Handle this
val body = response.body?.string();
if (body != null) {
if (body.contains("Login successful", ignoreCase = true)) {
binding.apply {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
}
}
})
}