Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin error while referencing Activity from Inner Class

I have an AsyncTask as an inner class inside my Activity written in Kotlin. Now, I tried to access the Activity from my AsyncTask's onPostExecute using this@MyActivity but Android Studio reports it as Unresolved Reference error. But this is the most common method suggested online for referencing the OuterClass from an 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 
    }


}

}
like image 942
Ikun Avatar asked Aug 28 '17 10:08

Ikun


2 Answers

You have to make class as 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
        }
    }
}
like image 149
vishal jangid Avatar answered Sep 23 '22 09:09

vishal jangid


The class MyTask must be defined as an inner class:

inner class MyTask(
    private var mContext: Context?,
    val pbMigrating: ProgressBar
) : AsyncTask<Void, Int, Void>()
{
    ...
}
like image 29
Piwo Avatar answered Sep 21 '22 09:09

Piwo