AndroidFlask
AndroidFlask copied to clipboard
Unable to connect to server
Hi,
I have implemented this project in Kotlin:
`class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }
fun connectServer(v: View?) {
val ipv4AddressView = findViewById<EditText>(R.id.IPAddress)
val ipv4Address = ipv4AddressView.text.toString()
val portNumberView = findViewById<EditText>(R.id.portNumber)
val portNumber = portNumberView.text.toString()
val postUrl = "http://$ipv4Address:$portNumber/"
val postBodyText = "Hello"
val mediaType: MediaType? = "text/plain; charset=utf-8".toMediaTypeOrNull()
val postBody = RequestBody.create(mediaType, postBodyText)
postRequest(postUrl, postBody)
}
fun postRequest(postUrl: String, postBody: RequestBody) {
val client = OkHttpClient()
val request: Request = Request.Builder()
.url(postUrl)
.post(postBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Cancel the post on failure.
call.cancel()
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread {
val responseText = findViewById<TextView>(R.id.responseText)
responseText.text = "Failed to Connect to Server"
}
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread {
val responseText = findViewById<TextView>(R.id.responseText)
try {
responseText.text = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
})
}
}`
The python server is up and running :
Can you help with this by any chance?
Hi @xdindincx,
Can you share the log please?