Kotlin error when linking activity from inner class

I have AsyncTask as an inner class inside my Activity, written in Kotlin. Now I tried to access the Activity from my AsyncTask onPostExecute using this@MyActivity, but Android Studio reports this as an unresolved link error. But this is the most common method offered online for referencing OuterClass from InnerClass. The code is as follows:

class MyActivity : AbstractAppPauseActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

override fun onResume() {
    super.onResume()
}

class MyTask(private var mContext: Context?, val pbMigrating: ProgressBar) :AsyncTask<Void, Int, Void>() {


    private var size: Long = 0

    override fun onPreExecute() {
        super.onPreExecute()
        ...

    }

    override fun doInBackground(vararg params: Void?): Void? {
        ...
        return null
    }

    override fun onProgressUpdate(vararg values: Int?) {
        super.onProgressUpdate(*values)
        pbMigrating.progress = values[0] as Int

    }

    override fun onPostExecute(result: Void?) {
        super.onPostExecute(result)
        this@MyActivity //<- Cannot Resolve error here 
    }


}

}
+4
source share
2 answers

You have to make the class inner

class MyActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

override fun onResume() {
    super.onResume()
} inner class MyTask(private var mContext: Context?, val pbMigrating: ProgressBar) : AsyncTask<Void, Int, Void>() {


    private var size: Long = 0

    override fun onPreExecute() {
        super.onPreExecute()


    }

    override fun doInBackground(vararg params: Void?): Void? {

        return null
    }

    override fun onProgressUpdate(vararg values: Int?) {
        super.onProgressUpdate(*values)
        pbMigrating.progress = values[0] as Int

    }

    override fun onPostExecute(result: Void?) {
        super.onPostExecute(result)
        this@MyActivity //<- Cannot Resolve error here
    }
}

}

+2
source

The MyTask class must be defined as an inner class:

inner class MyTask(private var mContext: Context?, val pbMigrating: ProgressBar) :AsyncTask<Void, Int, Void>() { ... }
0
source

Source: https://habr.com/ru/post/1684604/


All Articles