0
votes

It's my first app for android, and i have problem with applicationContext in runnable class. I want to make a server in kotlin (or java), but when i try to do it, a can't use applicationContext (when i use it in "override fun onCreate" all is ok. It's my class:

    class ServerReader2 : Runnable {

    var ss: ServerSocket? = null
    var mySocket: Socket? = null
    var dis: DataInputStream? = null
    var bufferedReader: BufferedReader? = null
    var message: String? = null
    var handler = Handler()
    override fun run() {
        try {
            ss = ServerSocket(7800)
            handler.post {
                //Toast.makeText(getApplicationContext(),"Waiting for client", Toast.LENGTH_SHORT).show();
            }
            while (true) {
                mySocket = ss!!.accept()
                dis = DataInputStream(mySocket!!.getInputStream())
                message = dis!!.readUTF()
                //handler.post { Toast.makeText(applicationContext, "message recived from client: $message", Toast.LENGTH_SHORT).show() }
                handler.post { Toast.makeText(applicationContext, "message recived from client: $message", Toast.LENGTH_SHORT).show() }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

This class is under "override fun onCreate(savedInstanceState: Bundle?)", but in my main class "class RemoteControl : AppCompatActivity()"

I know, i have to depend "ServerReader2" class od the AppCompatActivity, but i'dont know how (it's my first android app in kotlin). Before that i tried to do the same thing but in java in a separate file and i had the same problem.

1

1 Answers

0
votes

In order for you to access the private members of the parent class, use the inner keyword for your class.

In this case, you should write inner class ServerReader2 : Runnable.