Issues: 1. The request is not hitting my python flask server. 2. My app crashes whenever this code is run. *Note: I have used Postman to test the localhost address, which is successful
I am trying to create an okHttp request in my kotlin android application. I have implemented the needed dependencies in my build.gradle file:
implementation 'com.squareup.okhttp3:okhttp:3.10.0
edit: I included the Internet permission in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
I have tried using my IP as part of the URL, along with a few different localhost links and have determined that the URL is not the issue.
If I am not mistaken, the app crash error occurs during build (), but I cannot wrap my mind around why.
Ideally, this code would hit the rest API and return data (printed as text) on my login screen. After a couple of days of researching and trying other request methods, I am unable to find a solution.
val mTextviewResult: TextView = findViewById(R.id.text_view_result)
//http client
var client = OkHttpClient()
val url = "http://localhost:5000/test"
val request = Request.Builder()
.url(url)
.build()
Log.d(request.toString(), ": I build Request")
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d(url, ": I fail")
e.printStackTrace()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful()) {
Log.d(url, ": I success")
val myResponse = response.body()?.string()
this@LoginActivity.runOnUiThread(object : Runnable {
override fun run() {
mTextviewResult.setText(myResponse)
}
})
}
}
})