I have an app that communicates with a server during sockets. first I did this:
val sock = Socket("192.168.1.108", 5000)
and the app crashed because of the error: "android.os.NetworkOnMainThreadException", I read about it and I found a solution for that error and the solution is to create a syncTask as an inner class, and this is what I did:
class randomChat : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.chat_show)
HandleServer().execute()
}
inner class HandleServer: AsyncTask<String, String, String>() {
override fun doInBackground(vararg p0: String?): String {
val sock = Socket("192.168.1.108", 5000)
sock.getInputStream()
sock.use {
it.outputStream.write("hello socket world".toByteArray())
}
return "Good"
}
}
}
and that fixed the error, But did not fix my needs... basically, my needs are to have a conversion between the server and the user who use the app, the user will have an editText view and a button to send the data to the server and a textView that always change based on server data.
So: What I need to have is:
- open socket that receives data all the time from the server and updates a view in the activity
- I need to be able to have an editText in the activity that by user click it's send data to the server (with the socket)
Thank you very much !!!!!